gpt4 book ai didi

c++ - 执行类的成员函数

转载 作者:太空狗 更新时间:2023-10-29 21:02:33 26 4
gpt4 key购买 nike

我正在尝试以一种方式试验 C++11 线程,它接受一个类的成员函数作为线程构造函数的参数,如下面第 20 行标记的第一个代码片段所示。类定义在第二个代码片段中给出。编译这段代码时,我收到了第三个片段中显示的一堆错误。谁能告诉我我做错了什么?谢谢。

片段 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();

}

片段 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)’

最佳答案

显然这是一个 gcc 4.7 bug ...使用

std::thread t(&ServiceRegistrar::subscribe2TopologyServer, &sr1);

相反。

编辑:实际上,您可能不想将 sr1 复制到 t 的线程本地存储中,所以这样更好。

关于c++ - 执行类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com