std::线程重载未解决(使用正确的参数)

std::thread overload not resolved (with right arguments)

本文关键字:参数 线程 重载 未解决 std      更新时间:2023-10-16
#include <thread>
#include <iostream>
using namespace std;
class A
{
    public:
    A(){}
    void m(std::string* s)
    {
     cout<<*s;
    }
    void m(std::string s)
   {
     cout<<s;
   }
};    
int main()
{
 A a;
 string str="hi!n";
 std::thread(&A::m,a,&str);
}

这不会编译;它给出:

error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, A&, std::string*)’

如果我删除第二个成员,它会编译! 为什么?我不能在 std::thread 中使用重载方法?

可以,但您必须手动选择所需的重载:

std::thread th(static_cast<void (A::*)(std::string*)>(&A::m),a,&str);

或者你可以使用lambda:

std::thread th([&] { a.m(&str); });
附录:简而言之,无法

自动推断出这一点的原因是,编译器在搜索正确的构造函数时看起来只有皮肤深度。从std::thread类的相关构造函数模板中查找(制作!(正确的构造函数涉及模板参数推导,模板参数推导通常只看签名而不是函数模板的内部(在本例中为构造函数模板,对于我们的目的而言是相同的(。相关的构造函数模板是

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

。这本身并没有说明fargs在实现深度上的相互作用。其中没有足够的信息来确定只有一个超载的A::m可以工作,因此无法解决歧义,您必须手动执行此操作。

是否真的可能和/或实际地使编译器更深入地寻找来解决这种歧义是一个有趣的问题。我想这将是一个相当大的挑战。无论哪种方式,它还没有完成。