2017-04-12 11 views
1

페이지가 C++ thread error: no type named type이고 아래에서보고하는 것과 유사한 오류 메시지가 있습니다. 그 페이지의 대답은 내가 말할 수있는 한이 사건을 다루지 않습니다. 틀림없이, 내가 여기서 단순히 우둔한 무언가가 분명해야합니다.C++ 스레드 오류 - 클래스 매개 변수가있는 컴파일 타임 오류

저는 작업중인 C++ 프로그램에서 스레드를 사용하려고했습니다. boost::thread과 함께 초기 버전을 사용해도 문제가 없었습니다. 오늘 아침에 boost::thread 대신 std::thread을 사용하도록 코드를 다시 작성하려고 시도했습니다. 그 때 갑자기 내가 이해하지 못하는 컴파일 타임 오류가 발생했습니다. 문제의 코드를 다음 코드로 줄였습니다.

? 함수 인수로 내 자신의 사용자 정의 클래스 중 하나에 대한 참조를 전달하려고하면 프로그램이 컴파일되지 않습니다.

#include <iostream> 
#include <thread> 

class TestClass { } ; 

void testfunc1 (void)   { std::cout << "Hello World TF1" << std::endl ; } 
void testfunc2 (double val)  { std::cout << "Hello World TF2" << std::endl ; } 
void testfunc3 (TestClass & tc) { std::cout << "Hello World TF3" << std::endl ; } 

int main (int argc, char *argv[]) 
{ 
    std::thread t1 (testfunc1) ; 

    double tv ; 
    std::thread t2 (testfunc2, tv) ; 

    TestClass tc ; 
    std::thread t3 (testfunc3, tc) ; // compiler generates error here 

    return 0 ; 
} 

코드는 한 내가 코드의 마지막 줄 것을 주석으로 컴파일됩니다. 그러나 이것이 존재하면 다음과 같은 컴파일 타임 오류가 발생합니다.

$ g++ -std=c++11 test.cpp 
In file included from /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/thread:39:0, 
       from test.cpp:3: 
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/functional: In instantiation of ‘struct std::_Bind_simple<void (*(TestClass))(TestClass&)>’: 
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/thread:142:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(TestClass&); _Args = {TestClass&}]’ 
test.cpp:19:33: required from here 
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(TestClass))(TestClass&)>’ 
     typedef typename result_of<_Callable(_Args...)>::type result_type; 
                  ^
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/include/c++/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(TestClass))(TestClass&)>’ 
     _M_invoke(_Index_tuple<_Indices...>) 

분명히 유형 관련 문제가 있지만이 오류 메시지를 해독 할 수 없습니다. 문제가 뭔지 아십니까? (I는 윈도우 10 시스템에서 Cygwin에서 사용하는 일이 있지만, 그 문제 설명에 그와 관련이 있다고 생각하지 않습니다.)

답변

2

입니다 std::thread은 C++ 참조를 저장할 수 없기 때문에 std::vector<T&>이 존재하지 않는 것과 유사합니다. 따라서 참조를 전달하려면 표준 라이브러리에 reference wrapper이 있어야합니다. 이것은 기본적으로 언어 기반의 레퍼런스의 동작을 모방 한 후드 아래의 포인터입니다. std::refstd::cref (const 참조 용) 함수는 std::reference_wrapper의 객체를 만드는 데 사용됩니다 (템플릿 유형 공제 및 이름이 더 짧은 편리한 함수 임).

TestClass tc; 
std::thread t3(testfunc3, std::ref(tc)); 
+0

감사합니다. 혼자서 그걸 알아 내지 못했을거야. 매우 감사! –

1

당신이 std::ref 래퍼 사용할 필요가 참조를 전달하려면 :

std::thread t3 (testfunc3, std::ref (tc)) ; 
+0

감사 :

코드에서 추가해야 할 유일한 것은 그래서 같은 std::ref 함수 호출입니다! 도움을 감사하십시오. –