2017-02-20 67 views
0
#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 

以下代码是否正确?VS2015中的std :: ref错误

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

'的std ::螺纹T8(&C :: printMe,&c);' – cpplearner

+0

的https:// timsong- cpp.github.io/lwg-issues/2219 –

回答

0

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

1)它需要设置方法printMe作为一个静态方法来发送它的地址(printMe的地址),否则你发送一个相对地址到实例C

2)在创建线程t8的那一刻,你发送参照对象C作为参数,但功能printMe没有参数,所以你需要论证申报到printMe方法。

3)@carbarner告诉你,发送方法的指针为:std::thread t8(&C::printMe, &c);

产生的代码是:

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

struct C 
{ 
    static void printMe(C* ref) 
    { 
     std::cout << "Address of C ref: " << std::hex << ref << std::endl; 
    } 
}; 

struct D 
{ 
    void operator()() const 
    { 
     std::cout << "Operator D" << std::endl; 
    } 
}; 

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

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

    std::cout << "END" << std::endl; 
} 

并且输出是:

enter image description here