[英]Using C++ template with std::function and std::bind
我正在尝试创建一个模板类,该模板类又将在函数上生成包装器。 然后,该类将返回包装器作为结果。 我想使用模板来具有通用类,该通用类可与具有不同签名的任何函数一起使用,例如:
std::function<void()>task = std::bind(fun1, param1, param2);
std::function<int(int, int)>task = std::bind(fun2, param1, param2);
我想要这样的东西:
template <typename T1, typename T2>
class A {
A (string param1, string param2) {
// The created wrapper here i.e. 'task' will be returned by the class.
function<T1>task = bind(T2, param1, param2);
}
// Return the created wrapper in the constructor.
function<T1> returnWrapper() {
return task;
}
};
上面的代码大部分是伪代码,因为它无法编译,但可以让我对所要查找的内容有所了解。 有什么解决办法吗? 我认为应该不仅仅是为函数签名使用模板。 任何帮助将不胜感激。 我还希望能够在可能的情况下将任意数量的参数传递给“绑定”。
我想我解决了问题! 我必须定义一个类,该类在模板内使用两个类型名称,并将其中一个类型名称传递给std :: function,作为函数签名,然后在构造函数中使用第二个名称在std中定义curried函数(包装后的结果函数) :: bind。 然后一切正常! 可能有一些更好的解决方案,但这是我得到的最好的或差不多的清晰解决方案。 这是我找到的解决方案的摘要! 希望它对其他问题有帮助:
#include <iostream>
#include <functional>
using namespace std;
class A {
private:
template <typename T1, typename T2>
class B {
private:
function<T1>ff;
public:
B(T2 fun) {
ff = bind(fun, 1, placeholders::_1);
}
virtual ~B() {
}
int exec(int x) {
return ff(x);
}
};
static int myFun(int x, int y) {
return x + y;
}
public:
A() {
};
int test() {
B<int(int), int (*)(int, int)> b(&myFun);
return b.exec(10);
}
virtual ~A() {
};
};
int main() {
A a;
// Correct result is '11' since we pass 11 and 1 is in the curried function.
cout << "test result: " << a.test() << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.