c++ - 在 C++ 中不使用 lambda 的函数组合
问题描述
我想知道如何转换函数组合,但不使用 lambda。以下是来自https://stackoverflow.com/a/50035197的原始代码。
template<class Root, class... Branches> auto comp(Root &&root, Branches &&... branches) {
return [root, branches...](auto &&...args) {
return root(branches(std::forward<decltype(args)>(args)...)...);
};
}
int f(int x, int y) { return x + y; }
int g(int x) { return x * 19; }
int h(int x) { return x + 2; }
#include <iostream>
int main() {
auto fgh = comp(f, g, h);
std::cout << fgh(2) << '\n';
}
我试图在comp
不使用 lambda 的情况下模拟该函数,但编译失败:
template<class Root, class... Branches>
class compose2 {
Root root;
tuple<Branches...> branches;
public:
compose2(Root r, Branches... br) : root(r), branches(br...) {};
template <class... Args>
decltype(auto) operator()(Args... args) {
return root(branches((args)...)...); // compile error, because a tuple is not a parameter pack
}
};
我知道参数包不能是成员变量,所以我的第一个想法是使用元组来存储仿函数(branches
),但我被困在这里。branches
所以问题是,如何扩展comp
?
解决方案
推荐阅读
- java - JUnit测试中Spring引导应用程序的多个实例
- linux - 在 Ansible 中使用查找和复制模块
- corda - 在 Corda 中找不到现有的白名单文件
- python - 使用 Pykinect 和 Open CV 保存 Kinect RGB 和深度图像
- python - 使用 LSTM 预测多个步骤
- c# - 为什么我不能访问作为谓词传递给 LINQ 函数的方法体内的变量?
- ruby-on-rails - 什么可能导致 activerecord sum 返回错误的值?
- reactjs - 使用 recompose setStatic 并将其连接到 redux (nextjs)
- spring-cache - 更改子方法的缓存管理器
- android - Android - 将 Vuforia SDK 添加到现有的 android studio 项目