无法将类成员函数传递给另一个函数(std :: thread :: thread)

kha*_*vah 2 c++ member-function-pointers c++11 stdthread

看看这两个代码.

下面的代码工作正常.

void someFunction () {

    // Some unimportant stuff
}

MainM::MainM(QObject *parent) :
    QObject(parent)
{

    std::thread oUpdate (someFunction);

}
Run Code Online (Sandbox Code Playgroud)

此代码抛出错误:

void MainM::someFunction () {      //as a class member


}


MainM::MainM(QObject *parent) :
    QObject(parent)
{

    std::thread oUpdate (someFunction);

}
Run Code Online (Sandbox Code Playgroud)

错误:

error: no matching function for call to 'std::thread::thread(<unresolved overloaded function type>)'
     std::thread oUpdate (someFunction);
                                     ^
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 8

您不能创建一个指针到成员函数应用&只是名字.您需要完全合格的成员:&MainM::someFunction.

并通过传递将其绑定到实例this,例如

#include <thread>

struct MainM
{
    void someFunction() {
    }

    void main() 
    {
        std::thread th(&MainM::someFunction, this);
    }
};

int main()
{
    MainM m;
    m.main();
}
Run Code Online (Sandbox Code Playgroud)