无法std :: bind成员函数

时间:2016-02-10 20:48:45

标签: c++ c++11 stdbind

我写过以下课程:

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);
    }
}

这个代码本身在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    

我做错了什么?

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

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);
    }
}

我得到完全相同的错误。

4 个答案:

答案 0 :(得分: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

或(没有绑定参数这没有意义 - 如果你愿意,可以绑定abc

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

和那样的东西。

答案 1 :(得分:2)

您需要传入对SomeClass::test_function将运行的对象的引用(很可能是this)。 Cppreference描述了std::bind的工作原理。

另一个选择是使SomeClass::test_function成为静态成员函数,不需要将实例传递给bind。

答案 2 :(得分:2)

class DetailVC: UIViewController, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {/*code*/} 用于成员函数时,std::bind指针需要具有特征(即需要访问该类的实例)。可以作为this的参数捕获,也可以在以后调用绑定类型时作为参数捕获。

例如;

bind

答案 3 :(得分:1)

当您使用bind捕获指向成员函数的指针时,生成的bind对象的第一个参数必须是指合适类型的对象。由于您绑定到SomeClass::test_function,因此需要类型为SomeClass的对象才能应用它,因此test的第一个参数必须是SomeClass类型的对象或指向SomeClass类型对象的指针。对于初学者,请尝试这样称呼:

test(this, b, c);
相关问题