C++线程错误 - 带有类参数的编译时错误
C++ Thread Error - compile-time error with class argument
我发现页面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::ref
和std::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 ) ) ;
相关文章:
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 如何在常量计算表达式中获取编译时错误?
- C++根据调用的构造函数强制编译时错误
- 使用 std::iterator_traits<> 时编译时错误不明确
- is_same和variadic模板编译时错误无效转换
- 私有运营商删除会触发 GCC 和 Clang 的编译时错误,但不会在 MSVC 上触发编译时错误
- 运行时与编译时多态性:更好的可读性与编译时错误检查,更重要的是
- 引发编译时错误
- 为什么调用不明确的 ctor 时没有编译时错误?
- 在 sizeof 运算符上强制编译时错误
- 未经授权的私有类成员访问会产生编译时错误而不是运行时错误?
- 从Mac上的终端编译时C 错误
- 使用MINGW-W64使用-M32选项(32位代码)编译时错误
- 有时将函数作为参数发送时错误
- C++线程错误 - 带有类参数的编译时错误
- E0312,C2664尝试将向量对象作为函数参数传递时错误
- 如果编译时间构量参数是错误的,则生成编译时错误
- 尝试调用指向成员函数的函数指针时出现编译时错误
- 编译时错误:删除了联合默认构造函数
- 编译时错误,参数被识别为引用