C++ 如何使用c+绑定类中同名的成员函数之一+;11标准::绑定 类测试{ 公众: int work(){ 通过将其铸造到正确的类型: 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; } std::function f=std::bind(static_cast(&Test::work)和Test);

C++ 如何使用c+绑定类中同名的成员函数之一+;11标准::绑定 类测试{ 公众: int work(){ 通过将其铸造到正确的类型: 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; } std::function f=std::bind(static_cast(&Test::work)和Test);,c++,c++11,C++,C++11,在推导要绑定的模板参数时,编译器不在允许函数重载解析的上下文中-简单地说,它还没有走到这一步 推导出第一个参数确实是成员函数指针的名称后,它发现有两个名称相同但类型不同的函数 在这个阶段,他们都是同样有效的候选者(从模板参数推断的角度来看),因此这是不明确的 静态强制转换消除了歧义,因为通过在static\u cast中指定类型,我们将编译器推到了必须推导模板类型的阶段之外——我们自己承担了推导模板类型的责任 所以现在它所要做的就是超负荷解析 std::function<void()>

在推导要绑定的模板参数时,编译器不在允许函数重载解析的上下文中-简单地说,它还没有走到这一步

推导出第一个参数确实是成员函数指针的名称后,它发现有两个名称相同但类型不同的函数

在这个阶段,他们都是同样有效的候选者(从模板参数推断的角度来看),因此这是不明确的

静态强制转换消除了歧义,因为通过在
static\u cast
中指定类型,我们将编译器推到了必须推导模板类型的阶段之外——我们自己承担了推导模板类型的责任

所以现在它所要做的就是超负荷解析

std::function<void()> f = std::bind( static_cast<int (Test::*)()>(&Test::work), &test);
#包括
#包括
#包括
使用名称空间std;
课堂测试{
公众:
int work(){
cout试试这个(成员函数ptr):

intmain(){
试验;
typedef int(测试:*WKPtr)(无效);
WKPtr p=&Test::work;
std::function f=std::bind(p,&test);
f();
返回0;
}

为什么不跳过
std::bind
并使用lambda

int main(){
    Test test;
    typedef int(Test:: *WKPtr)(void);
    WKPtr p = &Test::work;
    std::function<int()> f = std::bind(p, &test);
    f();
    return 0;
}

作为奖励,您的可执行文件大小将更小,并且如果合适,编译器可以更轻松地内联代码。

首选
auto f=[&test]{test.work();}
任何绑定表达式lambda确实比std::bind更方便实现我的目标,在看到这些答案后,请注意,使用
std::function
而不是
auto
时,您要付出类型擦除的代价。请记住,谢谢Hanks,但解决方案似乎无法处理编译错误
C2562:std::_Callable_obj::_ApplyX:“void”函数返回值c:\program files(x86)\microsoft visual studio 12.0\vc\include\xrefwrap 283
visual studio 12是否完全兼容c++11?谢谢,但该解决方案似乎无法处理编译错误C2562:“std:\u Callable\u obj::\u ApplyX:“void”函数返回值 c:\program files(x86)\microsoft visual studio 12.0\vc\include\xref,谢谢,它可以工作。只是因为我不太熟悉c++11~
int main(){
    Test test;
    typedef int(Test:: *WKPtr)(void);
    WKPtr p = &Test::work;
    std::function<int()> f = std::bind(p, &test);
    f();
    return 0;
}
auto fp = [&t]() { t.test()};