我试图以一种方式试验C ++ 11线程,它接受类的成员函数作为线程构造函数的参数,如下面第20行标记的第一个代码片段所示。类定义在第二个代码片段中给出。编译此代码时,我收到第3个片段中显示的一堆错误。谁能告诉我我做错了什么?感谢。
SNIPPET 1:线程初始化(main_app.cpp)
#include <thread>
#include "ServiceRegistrar.hpp"
#define SERVER_TYPE 100065
#define SERVER_INST_LOWER 1
#define SERVER_INST_UPPER 2
#define TIMEOUT 500000
int main()
{
ServiceRegistrar sr1(SERVER_TYPE, TIMEOUT, SERVER_INST_LOWER, SERVER_INST_LOWER);
/*LINE 20 is the following*/
std::thread t(&ServiceRegistrar::subscribe2TopologyServer, sr1);
t.join();
sr1.publishForSRs();
}
SNIPPET 2:课程定义
class ServiceRegistrar
{
public:
ServiceRegistrar(int serverType, int serverTimeOut, int serverInstanceLower, int serverInstanceUpper)
: mServerType(serverType),
mServerTimeOut(serverTimeOut),
mServerInstanceLower(serverInstanceLower),
mServerInstanceUpper(serverInstanceUpper)
{ }
void subscribe2TopologyServer();
void publishForSRs();
void publishForServices();
private:
int mServerType;
int mServerTimeOut;
int mServerInstanceLower;
int mServerInstanceUpper;
};
SNIPPET 3:编译输出
$ g++ -g -c -Wall -std=c++11 main_app.cpp -pthread
In file included from /usr/include/c++/4.7/ratio:38:0,
from /usr/include/c++/4.7/chrono:38,
from /usr/include/c++/4.7/thread:38,
from main_app.cpp:8:
/usr/include/c++/4.7/type_traits: In instantiation of ‘struct std::_Result_of_impl<false, false, std::_Mem_fn<void (ServiceRegistrar::*)()>, ServiceRegistrar>’:
/usr/include/c++/4.7/type_traits:1857:12: required from ‘class std::result_of<std::_Mem_fn<void (ServiceRegistrar::*)()>(ServiceRegistrar)>’
/usr/include/c++/4.7/functional:1563:61: required from ‘struct std::_Bind_simple<std::_Mem_fn<void (ServiceRegistrar::*)()>(ServiceRegistrar)>’
/usr/include/c++/4.7/thread:133:9: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (ServiceRegistrar::*)(); _Args = {ServiceRegistrar&}]’
main_app.cpp:20:64: required from here
/usr/include/c++/4.7/type_traits:1834:9: error: no match for call to ‘ (std::_Mem_fn<void (ServiceRegistrar::*)()>) (ServiceRegistrar)’
答案 0 :(得分:4)
显然这是gcc 4.7 bug ...使用
std::thread t(&ServiceRegistrar::subscribe2TopologyServer, &sr1);
代替。
编辑:实际上,您可能不希望将sr1
复制到t
的线程本地存储中,所以无论如何这样做会更好。
答案 1 :(得分:0)
尝试:
std::thread t(std::bind(&ServiceRegistrar::subscribe2TopologyServer, sr1));
希望它有所帮助。