为什么我们需要 & in 绑定成员函数?

Why we need & in bind member function in boost?

本文关键字:绑定 成员 函数 in 我们 为什么      更新时间:2023-10-16

In boost doc:

Binding member functions can be done similarly. A bound member function takes in a pointer or reference to an object as the first argument. For instance, given:
struct xyz
{
void foo(int) const;
};
xyz's foo member function can be bound as:
bind(&xyz::foo, obj, arg1) // obj is an xyz object

为什么我们需要 &xyz::foo,而不仅仅是 xyz::foo?

int f(int a, int b)
{
return a + b;
}
std::cout << bind(f, 1, 2)() << std::endl;  

这样,我们就不会使用 &.

地址运算符(即&( 是获取指向成员函数的指针所必需的。对于非成员函数,它是可选的,因为函数到指针的隐式转换。

指向函数的指针可以使用非成员函数或静态成员函数的地址进行初始化。由于函数到指针的隐式转换,地址运算符是可选的: