VS2015中的std :: ref错误

时间:2017-02-20 21:05:58

标签: c++ c++11

#include <thread>
#include <iostream>
#include <functional>

struct C
{
    void printMe() const
    {}
};

struct D
{
    void operator()() const
    {}
};

int main()
{
    D d;
    std::thread t9(std::ref(d));    // fine
    t9.join();

    C c;
    std::thread t8(&C::printMe, std::ref(c));   // error in VS2015
    t8.join();

/*
1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: With the following template arguments:
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: '_Callable=void (__thiscall C::* )(void) const'
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: '_Types={std::reference_wrapper<C>}'
*/
}


http://ideone.com/bxXJem built without problems

以下代码是否正确?

std::thread t8(&C::printMe, std::ref(c));

1 个答案:

答案 0 :(得分:0)

不,它不会编译。要编译它并运行它,你需要:

1)需要将方法printMe设置为静态方法以发送其地址(printMe的地址),否则您将向实例C发送相对地址。

2)在创建线程t8时,您发送对象C的引用作为参数但函数{​​{1}}没有参数,所以你需要将参数声明为printMe方法。

3)正如@cpplearner告诉你的那样,将方法的指针发送为:printMe

结果代码是:

std::thread t8(&C::printMe, &c);

输出是:

enter image description here