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

'표준 : : 스레드 T8 &c);' – cpplearner

+0

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

답변

0

아니요, 컴파일되지 않습니다. 이를 컴파일하고 실행하려면 다음을 수행하십시오.

1) printMe 메소드를 정적 메소드로 설정하여 주소 (printMe의 주소)를 보내야합니다. 그렇지 않으면 상대 주소를 인스턴스 C으로 전송해야합니다. 스레드 t8을 생성의 순간

2), 당신은 인수했지만 인수가없는 기능 printMeC를 개체에 대한 참조를 전송하는, 그래서 당신은 printMe 방법으로 인수를 선언해야합니다.

3) @cpplearner가 설명한대로 메서드 포인터를 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; 
} 

그리고 출력은 다음과 같습니다 :

결과 코드는 (C : printMe,

enter image description here

관련 문제