C++:通用"call-functions-f-followed-by-g"方法?
C++: Generic "call-functions-f-followed-by-g" method?
是否可以有一个泛型方法,它接受两个函数f
和g
(都返回void
并接受相同类型的参数),并返回一个新函数,该函数接受与f
和g
相同类型的参数,并首先将f
应用于传递的参数,然后应用于g
?
具体来说,我想定义如下:
template <typename FunctionType>
// FunctionType is void(ArgType1 arg1, ArgType2 arg2, ..)
FunctionType CombineTwoFunctions(FunctionType f, FunctionType g) {
// Using the lambda syntax just for illustration:
return [f, g](ArgsOf(FunctionType) args) {
f(args);
g(args);
};
}
不是最优化的代码,但它可以工作。
在这个答案的make_function
的帮助下
template <typename ...Args>
std::function<void(Args...)> CombineTwoFunctionsHelper(std::function<void(Args...)> f, std::function<void(Args...)> g) {
return [f, g](Args ...args) {
f(args...);
g(args...);
};
}
template <typename F1, typename F2>
auto CombineTwoFunctions(F1 f1, F2 f2) -> decltype(make_function(f1)) {
return CombineTwoFunctionsHelper(make_function(f1), make_function(f2));
}
void print1(int i, std::string s) {
std::cout << "print1 " << i << s << std::endl;
}
void print2(int i, std::string s) {
std::cout << "print2 " << i << s << std::endl;
}
int main() {
auto fg = CombineTwoFunctions(print1, print2);
fg(1, "test");
}
Coliru 的完整代码
您应该能够通过向参数添加(通用)引用来改进它,并转发它们以避免复制。但请注意,不能移动一个参数两次。
正如@0x499602D2在评论中所说,C++14使其更容易
template <typename F1, typename F2>
auto CombineTwoFunctions(F1 f, F2 g) {
return [f, g](auto&& ...args) {
f(args...);
g(args...);
};
}
void print1(int i, std::string s) {
std::cout << "print1 " << i << s << std::endl;
}
void print2(int i, std::string s) {
std::cout << "print2 " << i << s << std::endl;
}
int main() {
auto fg = CombineTwoFunctions(print1, print2);
fg(1, "test");
}
Coliru 的完整代码
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- "error: no matching function for call to"构造函数错误
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 调用专用模板时出错"no matching function for call to [...]"
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- 如果子类中没有构造函数方法,则错误"no matching function for call to 'LGame::LGame(String&)'"
- Swift Call C 方法带有char **参数,并且需要操作char **参数
- C++:通用"call-functions-f-followed-by-g"方法?
- shared_ptr : "call of an object of a class type without appropriate operator() or conversion functio