1. 程式人生 > >C++ Thread類傳入某類的函式作為引數時,要在隨後傳入該類的物件

C++ Thread類傳入某類的函式作為引數時,要在隨後傳入該類的物件

std::thread 呼叫類的成員函式需要傳遞類的一個物件作為引數:

#include <thread>
#include <iostream>

class bar {
public:
  void foo() {
    std::cout << "hello from member function" << std::endl;
  }
};

int main()
{
  std::thread t(&bar::foo, bar());
  t.join();
}

如果是在類的成員函式中處理thread,傳入 this 即可,如:

std::thread spawn() {
    return std::thread(&blub::test, this);
  }