2017-02-20 52 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