首页 文章

C 11使用成员函数进行线程初始化编译错误[重复]

提问于
浏览
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()'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提供

1 回答

  • 20

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

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

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

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

相关问题