无法std :: bind成员函数

Xir*_*ema 2 c++ stdbind c++11

我写了以下课程:

class SomeClass {
private:
    void test_function(int a, size_t & b, const int & c) {
        b = a + reinterpret_cast<size_t>(&c);
    }
public:
    SomeClass() {
        int a = 17;
        size_t b = 0;
        int c = 42;
        auto test = std::bind(&SomeClass::test_function, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
        test(a, b, c);
    }
}
Run Code Online (Sandbox Code Playgroud)

就其本身而言,这段代码在IDE(Visual Studio 2015)中看起来很好,但是当我尝试编译它时,我收到以下错误:

Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'    Basic Server    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits  1441    
Error   C2672   'std::invoke': no matching overloaded function found    Basic Server    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits  1441    
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑:我也写了这个版本:

class SomeClass {
private:
    void test_function(int a, size_t & b, const int & c) {
        b = a + reinterpret_cast<size_t>(&c);
    }
public:
    SomeClass() {
        int a = 17;
        size_t b = 0;
        int c = 42;
        auto test = std::bind(&SomeClass::test_function, a, std::placeholders::_1, std::placeholders::_2);
        test(b, c);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到完全相同的错误.

Log*_*uff 7

您忘记了第四个参数,std::bind即您要调用非静态成员函数的实例.因为它不对(不存在的)类成员数据进行操作,所以我认为它应该是static,在这种情况下你不需要实例.

话虽这么说,如果你想绑定到非静态成员函数,你可以这样做:

auto test = std::bind(&SomeClass::test_function, this, std::placeholders::_1,
                      std::placeholders::_2, std::placeholders::_3);
// you can also bind *this
Run Code Online (Sandbox Code Playgroud)

或(这是没有意义的,没有绑定参数-绑定a,b,c如果你喜欢):

auto test = std::bind(&SomeClass::test_function,
                      std::placeholders::_1, std::placeholders::_2,
                      std::placeholders::_3, std::placeholders::_4);
test(this, a, b, c); // you can also pass a reference
Run Code Online (Sandbox Code Playgroud)

和那样的东西.

  • 也可以使函数静态,根本不需要实例. (3认同)