是否可以将重载方法传递给std :: thread [英] Is it possible to pass overloaded method to std::thread

查看:97
本文介绍了是否可以将重载方法传递给std :: thread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是线程技术的新手,我正尝试将重载方法传递给std :: thread,如下例所示

i am new to threading, i am trying to pass overloaded methods to std::thread like below example

#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;    
}

但是程序没有编译并抛出错误 no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, int)' std::thread t1(do_calculation,20);

but the program is not compiling and throwing error that no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, int)' std::thread t1(do_calculation,20);

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

Is there a way to call overloaded methods in thread?

推荐答案

您将需要强制转换函数以解决重载:

You will need to cast the functions to resolve overloading:

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

此外,您需要 join detach 您的线程,以免冒险游玩std::terminate:

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

这篇关于是否可以将重载方法传递给std :: thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆