是否可以使用折叠表达式实现以下目的?
template<class... Args>
auto foo(Args... args)
{
//calling foo(x0, x1, x2) should be exactly equivalent to
//calling fn(x2 ^ fn(x1 ^ fn(x0)))
}
最佳答案
您可以向 foo
添加一个强制参数,并检查您是否有其他带有 constexpr-if 的参数。
编辑:我不小心错过了它应该是折叠表达式的要求,所以这使用了包扩展和递归。
template <class T, class... Args>
constexpr auto foo(T&& x, Args&&... args) {
if constexpr (sizeof...(args)) {
return fn(x ^ foo(std::forward<Args>(args)...));
} else {
return fn(x);
}
}
这要求您在调用函数时反转参数:
foo(x2, x1, x0)
=> fn(x2 ^ fn(x1 ^ fn(x0)))
Demo
https://stackoverflow.com/questions/74084270/