C++ 如何在线程上运行成员函数?

C++ 如何在线程上运行成员函数?,c++,multithreading,c++11,templates,singleton,C++,Multithreading,C++11,Templates,Singleton,当我编译下面的代码时,我得到以下错误。帮帮我 错误: 错误C2276“&”:对绑定成员函数表达式执行非法操作 错误C3867'CCore::Run':非标准语法;使用“&”创建指向成员的指针 我不确定程序是否给了我一个错误。 我想运行核心类的“run”函数。 Core.cpp文件仅包含编译器创建的函数。 我在学英语,所以我还不太好。所以请理解整个代码 // main.cpp #include "Core.h" #include <thread> int main() { /

当我编译下面的代码时,我得到以下错误。帮帮我

错误: 错误C2276“&”:对绑定成员函数表达式执行非法操作
错误C3867'CCore::Run':非标准语法;使用“&”创建指向成员的指针

我不确定程序是否给了我一个错误。
我想运行核心类的“run”函数。
Core.cpp文件仅包含编译器创建的函数。

我在学英语,所以我还不太好。所以请理解整个代码

// main.cpp
#include "Core.h"
#include <thread>

int main()
{
    // The conditions below have been success
    if (CCore::GetInstance().Init())
    {
        // The code below fails to compile.
        // Error C3867 'CCore::Run': non - standard syntax; use '&' to create a pointer to member
        thread main_thread(CCore::GetInstance().Run);

        // Error C2276 '&': illegal operation on bound member function expression
        thread main_thread(&CCore::GetInstance().Run);

        main_thread.join();
    }
    return 0;
}
//main.cpp
#包括“Core.h”
#包括
int main()
{
//以下条件已获得成功
if(CCore::GetInstance().Init())
{
//下面的代码无法编译。
//错误C3867“CCore::Run”:非标准语法;使用“&”创建指向成员的指针
线程主线程(CCore::GetInstance().Run);
//错误C2276“&”:对绑定成员函数表达式执行非法操作
线程主线程(线程(&CCore::GetInstance().Run);
主螺纹连接();
}
返回0;
}
//Core.h
#布拉格语一次
#包括“Singleton.h”
#包括
使用名称空间std;
类别CCore:公共单身人士
{
公众:
CCore();
~CCore();
bool Init();
无效运行();
};
//Singleton.h
#布拉格语一次
模板
单件阶级
{
受保护的:
Singleton()=默认值;
~Singleton()=默认值;
公众:
静态T&GetInstance()
{
静态T实例;
返回实例;
}
单例(const Singleton&)=删除;
单例&运算符=(常量单例)=删除;
};

编译器告诉您问题:
Run()
不是免费函数。它是一种方法,即绑定到对象实例的函数。您有几个选项,但通常您要么让编译器为您合成一个可运行函数,要么自己编写一个自由函数:

void runCoreRun() {
  CCore::GetInstance().Run();
}

...
std::thread main_thread(&runCoreRun);
  • 让编译器来完成所有的工作:猜猜看,它可以为您生成单例,这有多酷

    std::thread main_thread([]{
      static CCore myCore;
      myCore.Run();
    });
    
  • 你想进入那个核心吗?当然

    std::future<CCore*> coreWhenDone = std::async([]{
      static CCore myCore;
      myCore.Run();
      return &myCore;
    });
    
  • 在您和编译器之间拆分工作:

    std::thread main_thread(std::bind(&CCore::Run, &CCore::GetInstance()));
    
  • 自己完成所有工作:

    void runCoreRun() {
      CCore::GetInstance().Run();
    }
    
    ...
    std::thread main_thread(&runCoreRun);
    

  • @JeJo感谢您编辑了无效的标记。如何:
    thread main_thread(&CCore::Run,CCore::GetInstance())@CAF-oh。。。我试过了,但没用。我可以问个问题吗?如果你有一个你经常提到的博客,请分享它。谢谢你解决了上面的问题。对于基本的答案,我不会参考太多我自己头脑之外的资源。Qt文档是我在使用C++前缀的IDE不可用时查找的API的主要资源,而我的头不提供帮助:我在GITHUB上保留了大多数我的答案。
    
    std::thread main_thread(std::bind(&CCore::Run, &CCore::GetInstance()));
    
    void runCoreRun() {
      CCore::GetInstance().Run();
    }
    
    ...
    std::thread main_thread(&runCoreRun);