C++ 为什么std::thread在';是否要求运行重载函数?

C++ 为什么std::thread在';是否要求运行重载函数?,c++,multithreading,c++11,visual-c++,C++,Multithreading,C++11,Visual C++,下面是我正在运行的代码,它在线程对象t1和t2中传递重载函数“myfunc”的行中抛出错误 (还附有评论) #包括 #包括 使用名称空间std; void myfunc(int x) { cout当您有作为参数传递的重载函数时,您需要帮助编译器 可能的解决办法: using f1 = void(*)(int); using f2 = void(*)(int, int); thread t1(static_cast<f1>(myfunc), 1); thread t2(static_

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

#包括
#包括
使用名称空间std;
void myfunc(int x)
{

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

可能的解决办法:

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

thread t1(static_cast<f1>(myfunc), 1);
thread t2(static_cast<f2>(myfunc), 1, 2);
使用f1=void(*)(int);
使用f2=void(*)(int,int);
螺纹t1(静态螺纹铸造(myfunc),1);
螺纹t2(静态螺纹铸造(myfunc),1,2);

或者,您可以稍后通过将
myfunc
包装到lambda中来请求重载解决方案:

std::thread t1([](auto... args) { myfunc(args...); }, 1);
std::thread t2([](auto... args) { myfunc(args...); }, 1, 2);

我敢打赌会有更多的错误输出,包括一些不明确的函数。当您将它们传递给线程构造函数时,编译器不知道应该使用哪个重载。编译器不理解
std::thread
的语义,也不知道该类最终会在内部调用第一个参数p在剩下的部分中使用assing。因此它无法选择正确的重载。要么为这两个函数指定不同的名称,要么您必须强制转换,如
std::thread t1(static_cast(myfunc),1);
std::thread t1([](auto... args) { myfunc(args...); }, 1);
std::thread t2([](auto... args) { myfunc(args...); }, 1, 2);