无法将调用成员函数的 lambda 作为 C++11 线程 ctor 参数传递



我想传递一个lambda调用成员函数作为参数到线程构造函数,但一直无法。下面是一个简单的例子:

#include <thread>
class Foo {
void run(void func()) {
func();
}
void bar() {
return;
}
void bof() {
std::thread thread(&Foo::run, this, [&]{bar();}); // This fails to compile
}
};

以上操作将导致以下错误:

$ g++ --std=c++11 -c funcThreadArg.cpp 
In file included from /usr/include/c++/4.8.2/thread:39:0,
from funcThreadArg.cpp:1:
/usr/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’:
/usr/include/c++/4.8.2/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Foo::*)(void (*)()); _Args = {Foo* const, Foo::bof()::__lambda0}]’
funcThreadArg.cpp:14:62:   required from here
/usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/4.8.2/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’
_M_invoke(_Index_tuple<_Indices...>)
^

我想做的是可能的吗?如果有,怎么做?

Foo::run()中使用std::function

class Foo {
void run(std::function<void()> func) {
func();
}
void bar() {
return;
}
void bof() {
std::thread thread(&Foo::run, this, [this](){ bar(); });
thread.join();
}
};

相关内容

最新更新