c++ thread 带参数编译错误:/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class st

4 篇文章 0 订阅

最近使用c++11 的标准thread库,发现传参的时候的bug,很隐密。

...
/usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::unordered_map<int, int>, int, int))(std::unordered_map<int, int>&, int, int)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
...

 

这个错误确实很神秘,但问题是thread_add它通过引用获取它的第一个参数,但是你按值传递它。这会导致仿函数类型推断错误。如果你想通过引用传递一些实际的函数std::bind或者像a 的main函数那样std::thread,你需要使用一个引用包装器(std::ref):

所以当你传的参数是引用的时候,GCC不会使用这个奇怪的消息进行编译。你可以通过使用带线程的引用包装器来摆脱它

t[0] = thread(thread_add, std::ref(ht), 0, 9);
t[1] = thread(thread_add, std::ref(ht), 10, 19);

这将成功编译。并且线程使用的每个引用都将引用相同的对象。

 

这是一种传参时是引用的报错,这时候用std::ref()装饰一下就可以了。

还有一种是类的this指针问题。具体的话参照我找到的问题文章看下:

https://segmentfault.com/q/1010000004413576

http://stackoverflow.com/questions/28950835/c-error-no-type-named-type-in-class-stdresult-ofvoid-stdunordered

 

 

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值