【问题标题】:C++ Thread Error - compile-time error with class argumentC++ 线程错误 - 带有类参数的编译时错误
【发布时间】:2017-04-12 17:32:15
【问题描述】:

我找到了页面C++ thread error: no type named type,其中包含与我在下面报告的错误消息类似的错误消息。据我所知,该页面上的答案不包括这种情况。诚然,这里一定有一些简单的东西我对此一无所知。

我一直在尝试在我正在处理的 C++ 程序中使用线程。我有一个使用boost::thread 的初始版本,没有任何问题。今天早上,我尝试重写我的代码以使用std::thread 而不是boost::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...>)

显然存在某种与类型相关的问题,但我无法解读此错误消息。知道问题是什么吗? (我碰巧在 Windows 10 机器上使用 Cygwin,但我认为这与所描述的问题无关。)

【问题讨论】:

    标签: c++ multithreading c++11 cygwin


    【解决方案1】:

    那是因为std::thread 不能存储C++ 引用,这类似于std::vector&lt;T&amp;&gt; 不能存在。因此,为了传递引用,标准库中有一个reference wrapper。它基本上是引擎盖下的指针,它模仿了一些语言方面的参考行为。 std::refstd::cref(用于 const 引用)函数用于创建 std::reference_wrapper 的对象(它们是方便的函数,因为它们具有模板类型推导和更短的名称)。

    您唯一需要在代码中添加的是std::ref 函数调用,如下所示:

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

    【讨论】:

    • 谢谢!我自己永远也想不通。非常感谢!
    【解决方案2】:

    要传递引用,您需要使用 std::ref 包装器:

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

    【讨论】:

    • 谢谢!感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多