【发布时间】:2023-03-19 10:25:02
【问题描述】:
我刚刚开始使用 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()’
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::*&&)()'的转换
/usr/include/c++/4.6/thread:128:5: 注意:std::thread::thread(std::thread&&)
/usr/include/c++/4.6/thread:128:5: 注意:没有已知的参数 1 从‘’到‘std::thread&&’的转换
/usr/include/c++/4.6/thread:124:5: 注意:std::thread::thread()
/usr/include/c++/4.6/thread:124:5: 注意:候选人需要 0 个参数,提供 1 个
【问题讨论】:
-
尝试一个简单的 lambda:
[&](){obj.foo();}。 Full code here. -
+1:小而完整的代码示例和完整的错误消息。请注意,这里的代码 sn-p 格式不喜欢标签(我已经在这篇文章中为你解决了这个问题)。
-
感谢 Angew,我一定会在以后的帖子中更改标签。
标签: c++ multithreading class c++11 member