C++线程错误 - 带有类参数的编译时错误

C++ Thread Error - compile-time error with class argument

本文关键字:参数 编译时错误 线程 错误 C++      更新时间:2023-10-16

我发现页面C++线程错误:没有名为 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,但我认为这与所描述的问题无关。

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

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

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

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

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