std::线程重载未解决(使用正确的参数)
std::thread overload not resolved (with right arguments)
#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 );
。这本身并没有说明f
和args
在实现深度上的相互作用。其中没有足够的信息来确定只有一个超载的A::m
可以工作,因此无法解决歧义,您必须手动执行此操作。
是否真的可能和/或实际地使编译器更深入地寻找来解决这种歧义是一个有趣的问题。我想这将是一个相当大的挑战。无论哪种方式,它还没有完成。
相关文章:
- C++线程中,没有重载函数接受 X 参数
- C++ 中的线程不能使用参数
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- C++线程找不到函数作为参数(链接器)
- 如何将带有参数的方法传递给线程以执行?
- 为什么 beginthreadex 线程参数变量在父线程中没有更新
- 如何将参数传递给已经开始运行的线程
- 线程构造函数周围的可变参数模板包装器无法编译
- 线程函数中的c++参数更改
- 参数包推导不一致 int 和 int& 在可变参数模板化成员函数中创建运行成员函数的线程
- 线程函数参数的前向声明不起作用
- 带参数的线程调用库函数
- 错误:静态断言失败:std ::线程参数必须在转换为rvalues后不可行
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- 错误 C2064:term 的计算结果不是采用 1 个参数的函数 - 关于线程的一些东西
- 通过将两个参数包的元素线程化为类型对来解压缩这两个参数包
- 提升线程:术语的计算结果不为 0 个参数
- C++线程错误 - 带有类参数的编译时错误
- 在 C++11 中,如何不将参数传递给线程
- 在单独的线程中使用参数启动成员函数