如何使用 c++11 std::bind 绑定类中同名的成员函数之一

How to bind one of member functions of the same name in a class, with c++11 std::bind

本文关键字:成员 函数 c++11 何使用 std bind 绑定      更新时间:2023-10-16
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)(我们将其命名为Test(,但发生编译器错误,说无法确定使用哪个被覆盖的函数。

不能改变类测试,因为它属于一个库,如何实现我的目标?提前感谢!

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

auto fp = [&t]() { t.test()};

作为奖励,您的可执行文件大小会更小,并且您的编译器在适当的情况下更容易内联代码。

通过将其转换为正确的类型:

std::function<void()> f = std::bind( static_cast<int (Test::*)()>(&Test::work), &test);

在推导要绑定的模板参数时,编译器不在允许函数重载解析的上下文中 - 简单来说,它还没有那么远。

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

在这个阶段,它们都是同样有效的候选者(从模板参数推导的角度来看(,因此它是模棱两可的

静态强制转换消除了歧义,因为我们正在将编译器推到它必须推断模板类型的阶段之外 - 我们自己承担了模板类型推断的责任 - 通过在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;
}

试试这个(成员函数ptr(:

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