我有一个在 worker 线程中执行另一个功能的函数:
void run_in_worker_thread( std::function< void( ) > proc )
现在,我想实现函数 schedule(),该函数将 proc()函数作为参数,并返回通过 run_in_worker_thread()在工作线程中执行 proc()的函数。
这是我的实现:
#include <iostream>
#include <functional>
using namespace std;
class Test
{
public:
void run_in_worker_thread( std::function< void( ) > proc )
{
std::cout << "execute in worker thread\n";
proc();
}
template < class... TArgs >
std::function< void( TArgs... ) >
schedule( std::function< void( TArgs... ) > proc )
{
std::function< void( TArgs... ) > f
= [this, proc]( TArgs... args ) { run_in_worker_thread( [=]( ) { proc( args... ); } ); };
return f;
}
};
int main()
{
Test test;
std::function<void(int, int)> my_funciton =
[](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
auto f2 = test.schedule( my_funciton );
f2(1, 2);
return 0;
}
问题是我的 schedule()需要std::function作为参数。例如,以下调用导致编译错误:
auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
auto f2 = test.schedule( my_funciton );
最佳答案
问题是std::function
是可调用对象周围的多态包装。 Lambda不是std::function
。就像字符串文字不是std::string
一样。在第一个示例中,您将执行以下操作:
std::function<void(int, int)> my_funciton =
[](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
您正在从lambda构造
std::function
。 schedule
函数能够推断出该函数的签名而不会出现问题。在第二个示例中,您将执行以下操作:
auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
然后,您将收到一个错误,因为
std::function<void (Args...)>
无法与lambda匹配。解决方案是允许schedule
接受任何可调用的对象,而不仅仅是std::function
。template <typename Func>
auto schedule(Func proc) {
return [this, proc](auto... args) {
run_in_worker_thread([=]() {
proc(args...);
});
};
}
关于c++ - 将N-arg函数包装到另一个函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60243634/