gpt4 book ai didi

c++ - 你能用折叠表达式实现 fn(x1 ^ fn(x0)) 吗?

转载 作者:行者123 更新时间:2023-12-05 09:01:09 25 4
gpt4 key购买 nike

是否可以使用折叠表达式实现以下目的?

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

关于c++ - 你能用折叠表达式实现 fn(x1 ^ fn(x0)) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74084270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com