下面是我正在运行的代码,它在我在线程对象 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/