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

deb*_*man 7 c++ c++11

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;
}
Run Code Online (Sandbox Code Playgroud)

如上面的代码,我想绑定void work(void)一个类的成员函数(让我们将它命名为Test),但是发生编译错误,说无法确定使用哪个重写函数.

我不能改变类Test因为它属于lib,如何实现我的目标?提前致谢!

jro*_*rok 5

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

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


The*_*ROE 5

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

auto fp = [&t]() { t.test()};
Run Code Online (Sandbox Code Playgroud)

作为奖励,您的可执行文件大小将更小,如果适当,您的编译器可以更容易地内联代码.