我想实现一个像thread
构造函数一样工作的函数调用程序。例如
std::thread second (bar,0);
将启动一个线程,该线程使用单个参数 0
调用 bar
。我也想做同样的事情,但我不知道怎么做。
例如,给定:
void myFunc(int a){
cout << a << endl;
}
我愿意:
int main() {
caller(myFunc,12);
}
使用参数12
调用myFunc
。
最佳答案
std::bind
将使用任意一组参数从任何可调用对象创建一个可调用对象,就像 thread
构造函数所做的那样。所以只需将它包装在一个调用它的函数中:
template <typename... Args>
auto caller(Args &&... args) {
return std::bind(std::forward<Args>(args)...)();
}
请注意,auto
返回类型需要 C++14 或更高版本。对于 C++11,您必须返回 void
,或指定类型:
auto caller(Args &&... args)
-> decltype(std::bind(std::forward<Args>(args)...)())
关于C++ 通用函数调用器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29919405/