使用参数包在C++中组合 lambda 函数

Compose lambda function in C++ using parameter pack

本文关键字:组合 lambda 函数 C++ 参数      更新时间:2023-10-16

我是 C++ 14 的新手,我想将可变长度的 lambda 函数组合成单个 lambda,我应该怎么做?以下是我目前的工作

#include <iostream>
template<typename Ftype>
Ftype compose(const Ftype & fn) {
return fn;
}
template<typename Ftype, typename... Other>
auto compose(Ftype fn, Other... other) {
return [=](auto x){return other(fn(x))...;};
}        ➤ expression contains unexpanded parameter pack 'other'
int main(void) {
auto add_func = [](const int x) { return x * 7; };
auto sub_func = [](const int x) { return x + 1; };
int res = compose(add_func, sub_func)(1);
std::cout << "Result: " << res << "n";
}

但是我编译失败了,我想我可能以某种方式错误地使用了lambda或可变参数。 有人可以帮助我吗?

您的"递归"案例不包含对compose的调用,这应该暗示您在哪里混淆了;)

return [=](auto x){ return compose(other...)(fn(x)); };