加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 是否可以将重载方法传递给std :: thread

发布时间:2020-12-16 10:44:40 所属栏目:百科 来源:网络整理
导读:我是线程新手,我试图将重载方法传递给std :: thread,如下例所示 #include iostream #include thread int do_calculation(int x) { std::coutx; } float do_calculation(float x) { std::coutx; } int main() { std::thread t1(do_calculation,20); std::thre
我是线程新手,我试图将重载方法传递给std :: thread,如下例所示

#include <iostream>    
#include <thread>    

int do_calculation(int x)    
{    
   std::cout<<x;    
}    

float do_calculation(float x)    
{    
   std::cout<<x;    
}    

int main()    
{    
   std::thread t1(do_calculation,20);    
   std::thread t2(do_calculation,200.0f);    
   return 0;    
}

但程序没有编译并抛出错误
没有用于调用’std :: thread :: thread(< unresolved overloaded function type>,int)’的匹配函数
????std :: thread t1(do_calculation,20);

有没有办法在线程中调用重载方法?

解决方法

您需要转换函数来解决重载:

std::thread t1(static_cast<int(*)(int)>(do_calculation),20);    
std::thread t2(static_cast<float(*)(float)>(do_calculation),200.0f);

此外,你需要joindetach你的线程,以免你冒险去std :: terminate旅行:

t1.join();
t2.join();

Demo

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读