【问题标题】:Cannot pass class member-function to another function(std::thread::thread)无法将类成员函数传递给另一个函数(std::thread::thread)
【发布时间】:2013-09-18 18:38:15
【问题描述】:

看看这两个代码。

下面的代码可以正常工作。

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);
                                     ^

【问题讨论】:

  • Start thread with member function 的可能重复项 - 您是否尝试过搜索现有答案?
  • @JonathanWakely 是的,对不起。它不仅与 std::thread 相关,所以...

标签: c++ c++11 member-function-pointers stdthread


【解决方案1】:

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

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

#include <thread>

struct MainM
{
    void someFunction() {
    }

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

int main()
{
    MainM m;
    m.main();
}

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2017-03-22
    • 2021-05-30
    • 2016-02-18
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多