c++ - 为什么 std::thread 在被要求运行重载函数时会抛出错误?

标签 c++ multithreading c++11 visual-c++

下面是我正在运行的代码,它在我在线程对象 t1 和 t2 中传递重载函数“myfunc”的行中抛出错误 (也用评论标识)

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

    void  myfunc(int x)
        {
            cout << x << endl;
        }

    void  myfunc(int  x,int y)
    
    {
        
        cout << x << " " << y << endl;
    }

    int main()
    {
    
        thread t1(myfunc,1);//error here
        thread t2(myfunc, 1,2);//error here
        
        t1.join();
        t2.join();
        return 0;
    }

错误说明:

错误 1: 错误(事件)E0289 构造函数“std::thread::thread”的实例不匹配参数列表参数类型为:(unknown-type,int)

错误 2: 错误(事件)E0289 构造函数“std::thread::thread”的实例不匹配参数列表参数类型为:(unknown-type,int,int)

最佳答案

当您有作为参数传递的重载函数时,您需要帮助编译器。

可能的解决方案:

using f1 = void(*)(int);
using f2 = void(*)(int, int);

thread t1(static_cast<f1>(myfunc), 1);
thread t2(static_cast<f2>(myfunc), 1, 2);

关于c++ - 为什么 std::thread 在被要求运行重载函数时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67660976/

相关文章:

c++ - 带有特定键盘键的qt橡皮筋选择

c# - 这种锁定和管理锁定异常的解决方案有什么问题?

Winforms多线程场景问题

java - 如何在其他线程上正确执行数据库调用?

c++ - 前向声明困惑

c++ - 为什么 snprintf 在打印单个数字时始终比 ostringstream 快 2 倍?

c++ - 静态字符数组和指针内存

c++ - 可能的模板和 constexpr——如果不兼容

c++ - 使重写的虚函数成为非虚函数的目的

c++ - 使用 C++11 Lambda 函数更改 vector(list, deque...) 中的所有元素