class Test{
public:
int work(){
cout << "in work " << endl;
return 0;
}
void work(int x){
//cout << "x = " << x << endl;
cout << "in work..." << endl;
}
};
int main(){
Test test;
std::function<void()> f = std::bind(&Test::work, &test);
thread th(f);
th.join();
return 0;
}正如上面的代码一样,我希望绑定类的成员函数void work(void) (让我们命名为测试),但是会发生编译器错误,说明无法确定要使用哪个被覆盖的函数。
我不能更改类测试,因为它属于一个库,如何实现我的目标?提前感谢!
发布于 2015-11-05 11:42:44
为什么不跳过std::bind并使用lambda呢?
auto fp = [&t]() { t.test()};更重要的是,您的可执行文件的大小将更小,并且您的编译器在适当的情况下可以更容易地内联代码。
发布于 2015-11-05 09:20:03
通过将其转换为正确的类型:
std::function<void()> f = std::bind( static_cast<int (Test::*)()>(&Test::work), &test);发布于 2015-11-05 09:33:26
在推导要绑定的模板参数时,编译器并不是在允许函数过载解析的上下文中--要简化它,它还没有达到这个目的。
在推导出第一个参数确实是成员函数指针的名称之后,它发现有两个名称相同但类型不同的函数。
在这个阶段,它们都是同样有效的候选对象(从模板参数推导的角度来看),因此它是不明确的。
静态转换消除歧义,因为我们将编译器推到必须推断模板类型的阶段--我们自己承担了模板类型推断的责任--通过在static_cast中指定类型来消除歧义。
所以现在它所要做的就是解决过载问题。
#include <functional>
#include <thread>
#include <iostream>
using namespace std;
class Test{
public:
int work(){
cout << "in work " << endl;
return 0;
}
void work(int x){
//cout << "x = " << x << endl;
cout << "in work..." << endl;
}
};
int main(){
Test test;
// only overload resolution required here
auto fp = static_cast<int (Test::*)()>(&Test::work);
// type is now unambiguous and overload resolution is already done
std::function<void()> f = std::bind(fp, &test);
thread th(f);
th.join();
return 0;
}https://stackoverflow.com/questions/33540482
复制相似问题