我有一个包含成员函数的类,我希望将其传递给std::thread
的构造函数。
#include <thread>
#include <iostream>
struct StatsClientImpl
{
std::thread t;
size_t q_len;
StatsClientImpl() : q_len(0)
{
t = std::thread(&StatsClientImpl::de_q, this);
}
~StatsClientImpl()
{
if (t.joinable())
t.join();
}
void de_q()
{
std::cout << "in de_q\n";
}
};
int main()
{
StatsClientImpl s;
}
我收到以下错误:
/Users/apple/platform/stats-client/src/main/cpp/StatsClientImpl.cpp:21:17: error: no matching constructor for initialization of 'std::thread'
std::thread te(&StatsClientImpl::de_q, this);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:374:9: note: candidate constructor template not viable: requires single argument '__f', but 2 arguments were provided
thread::thread(_Fp __f)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:263:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
thread(const thread&);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:270:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
thread() _NOEXCEPT : __t_(0) {}
答案 0 :(得分:1)
C ++ 11线程允许直接调用非静态方法。您使用的语法仅用于此,只需将de_q_caller替换为de_q:
t = std::thread(&StatsClientImpl::de_q, this);
更新:因为您的编译器似乎不允许这样做,请尝试
t = std::thread(std::bind(&StatsClientImpl::de_q, this));
clang编译器可能需要添加以下编译器选项:
-std=c++11