c ++ 11线程类如何使用类成员函数 [英] c++11 Thread class how to use a class member function
本文介绍了c ++ 11线程类如何使用类成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程式如下所示
#include <iostream>
#include <thread>
class A {
public:
void foo(int n ) { std::cout << n << std::endl; }
};
int main()
{
A a;
std::thread t1(&A::foo, std::ref(a), 100);
t1.join();
return 0;
}
当我使用下面的命令编译时遇到错误
When I compile it using the following command I get errors
g++ -o main main.cc -lpthread -std=c++11
错误:
In file included from /usr/local/include/c++/4.8.2/thread:39:0,
from check.cc:2:
/usr/local/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (A::*)(int)>(std::reference_wrapper<A>, int)>’:
/usr/local/include/c++/4.8.2/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (A::*)(int); _Args = {std::reference_wrapper<A>, int}]’
check.cc:13:42: required from here
/usr/local/include/c++/4.8.2/functional:1697:61: error:no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (A::*)(int)>(std::reference_wrapper<A>, int)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/local/include/c++/4.8.2/functional:1727:9: error:no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (A::*)(int)>(std::reference_wrapper<A>, int)>’
_M_invoke(_Index_tuple<_Indices...>)
^
推荐答案
这不是参考包装器的正确位置。一个简单的指针足够了,并达到了所需的结果:
This isn't the right place for a reference wrapper. A simple pointer suffices, though, and achieves the desired result:
std::thread t1(&A::foo, &a, 100);
这篇关于c ++ 11线程类如何使用类成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文