我刚刚开始使用 C++ 11 线程,并且一直在努力解决一个(可能是愚蠢的)错误。这是我的示例程序:
#include <iostream>
#include <thread>
#include <future>
using namespace std;
class A {
public:
A() {
cout << "A constructor\n";
}
void foo() {
cout << "I'm foo() and I greet you.\n";
}
static void foo2() {
cout << "I'm foo2() and I am static!\n";
}
void operator()() {
cout << "I'm the operator(). Hi there!\n";
}
};
void hello1() {
cout << "Hello from outside class A\n";
}
int main() {
A obj;
thread t1(hello1); // it works
thread t2(A::foo2); // it works
thread t3(obj.foo); // error
thread t4(obj); // it works
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
是否可以从纯成员函数启动线程?如果不是,我如何从对象obj包装我的foo函数以创建这样的线程?提前致谢!
这是编译错误:
thread_test.cpp:在函数'int main()'中:thread_test.cpp:32:22:错误:没有匹配函数调用'std::thread::thread()'</p>
thread_test.cpp:32:22:注意:候选人是:
/usr/include/c++/4.6/thread:133:7: 注意:std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (A::*)(), _Args = {} ]
/usr/include/c++/4.6/thread:133:7: 注意:没有已知的参数 1 从 '' 到 'void (A::*&&)()' 的转换</p>
/usr/include/c++/4.6/thread:128:5: 注意:std::thread::thread(std::thread&&)
/usr/include/c++/4.6/thread:128:5: 注意:没有已知的参数 1 从 '' 到 'std::thread&&' 的转换</p>
/usr/include/c++/4.6/thread:124:5: 注意:std::thread::thread()
/usr/include/c++/4.6/thread:124:5:注意:候选人需要 0 个参数,提供 1 个