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

Cannot pass class member-function to another function(std::thread::thread)

本文关键字:函数 thread std 另一个 成员 不能      更新时间:2023-10-16

看看这两个代码。

下面的代码工作正常。

void someFunction () {
    // Some unimportant stuff
}
MainM::MainM(QObject *parent) :
    QObject(parent)
{
    std::thread oUpdate (someFunction);
}

此代码引发错误:

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

}

MainM::MainM(QObject *parent) :
    QObject(parent)
{
    std::thread oUpdate (someFunction);
}

错误:

error: no matching function for call to 'std::thread::thread(<unresolved overloaded function type>)'
     std::thread oUpdate (someFunction);
                                     ^
不能

通过将&应用于名称来创建指向成员函数的指针。您需要完全合格的成员:&MainM::someFunction

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

#include <thread>
struct MainM
{
    void someFunction() {
    }
    void main() 
    {
        std::thread th(&MainM::someFunction, this);
    }
};
int main()
{
    MainM m;
    m.main();
}
相关文章: