std::bind绑定成员函数,为什么第二个参数必须绑定对象地址

td::bind

这个函数在绑定成员函数的时候,必须显示指明实例化后的对象的地址。
因为在此处bind的第一个参数是 的成员函数的地址,没有经过实例化,所以不是内存中真正的位置,需要配合实例化后的对象的地址才可以一起使用。

struct Foo {
    void print_sum(int n1, int n2)
    {
        std::cout << n1+n2 << '\n';
    }
    int data = 10;
};
int main() 
{
    Foo foo;
    auto f = std::bind(&Foo::print_sum, &foo, 95, std::placeholders::_1);
    f(5); // 100
}

上面的 auto f = std::bind(&Foo::print_sum, &foo, 95, std::placeholders::_1);如果改为

 auto f = std::bind(&Foo::print_sum, 95, std::placeholders::_1);则编译报错 

猜你喜欢

转载自blog.csdn.net/danshiming/article/details/114208555