来自现有 class 的 C++11 线程
C++11 thread from an existent class
我确定这是一个简单的设计错误,但我不确定该怎么做。
我想从 class 的实例生成一个线程。具体来说:
class Foo
{
public:
void bar() { /*do stuff*/ }
};
用法:
int main()
{
Foo foo_instance();
std::thread foo_thread(foo_instance.bar);
foo_thread.join();
return 0;
}
当我编译这个更详细的版本时,我得到 invalid use of non-static member function
指的是 std::thread foo_thread(foo_instance.bar);
.
行
那么,我在这里误解了什么?我希望在将对象转入线程之前初始化对象并 "functional",但显然我没有正确使用这些工具。
成员函数的调用方式与自由函数不同,因为隐式 this
、std::thread
需要一个 Callable
,这比自由更灵活一点功能。
在你的情况下,最简单的是使用 lambda :
std::thread foo_thread( [&] { foo_instance.bar(); } );
我确定这是一个简单的设计错误,但我不确定该怎么做。
我想从 class 的实例生成一个线程。具体来说:
class Foo
{
public:
void bar() { /*do stuff*/ }
};
用法:
int main()
{
Foo foo_instance();
std::thread foo_thread(foo_instance.bar);
foo_thread.join();
return 0;
}
当我编译这个更详细的版本时,我得到 invalid use of non-static member function
指的是 std::thread foo_thread(foo_instance.bar);
.
那么,我在这里误解了什么?我希望在将对象转入线程之前初始化对象并 "functional",但显然我没有正确使用这些工具。
成员函数的调用方式与自由函数不同,因为隐式 this
、std::thread
需要一个 Callable
,这比自由更灵活一点功能。
在你的情况下,最简单的是使用 lambda :
std::thread foo_thread( [&] { foo_instance.bar(); } );