多线程与函数重载问题

发布于 2022-09-11 19:58:58 字数 884 浏览 21 评论 0

请问一下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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

身边 2022-09-18 19:58:58

你遇到的问题是模板参数推导失败,这是直接由函数重载引起的。换句话说,当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构造函数的形式参数,而是一个副本。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文