13

我刚刚开始使用 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 个

4

1 回答 1

20

你需要一个不带参数的可调用对象,所以

thread t3(&A::foo, &obj);

应该做的伎俩。这具有创建调用的可调用实体的A::foo效果obj

原因是非静态成员函数A采用类型的隐式第一个参数(可能是 cv 限定的)A*。当你打电话时,obj.foo()你实际上是在打电话A::foo(&obj)。一旦你知道了,上面的咒语就很有意义了。

于 2013-03-15T14:09:53.703 回答