多线程与函数重载问题

请问一下c++写多线程是不是不支持重载函数或者函数模板吗,或是需要调用其他什么方法实现吗?

下面是我的测试程序

#include<iostream>
#include<thread>
#include <string>
using namespace std;

void show(const char str[], const int id)
{
    cout << "线程 " << id + 1 << " :" << str << endl;
}
void show( string& str, const int id)
{
    cout << "线程 " << id + 1 << " :" << str << endl;
}
//template<class T, class U>
//void show(T str, U id)
//{
//    cout << "线程 " << id + 1 << " :" << str << endl;
//}

int main()
{
    //show("1.hello cplusplus!", 0);
    
    thread t1(show, "1.hello cplusplus!", 0);
    t1.join();

    string s = "2.cplusplus!";
    thread t2(show, std::ref(s) , 1);
    t2.join();

    thread t3(show, "3.hello!", 2);
    t3.join();
    return 0;
}
阅读 4.3k
1 个回答

你遇到的问题是模板参数推导失败,这是直接由函数重载引起的。换句话说,当show是函数重载时,便不能直接以show作为std::thread的构造函数的实际参数。

可以用lambda expression

thread t1([]() { show("1.hello cplusplus!", 0); });
t1.join();

// C++14
thread t3([](auto&&... args) { show(std::forward<decltype(args)>(args)...); }, "3.hello!", 2);
t3.join();

或者用static_cast

string s = "2.cplusplus!";
thread t2(static_cast<void (*)(std::string &, int)>(show), std::ref(s), 1);
t2.join();

来解决这个问题。

PS: lambda expression的第二段代码样例里转发的不是thread构造函数的形式参数,而是一个副本。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题