lxgeek
lxgeek

Reputation: 1814

Why we need & in bind member function in boost?

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

Why we need &xyz::foo, not just xyz::foo?

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

In this way, we don't use &.

Upvotes: 1

Views: 51

Answers (1)

songyuanyao
songyuanyao

Reputation: 172994

The address-of operator (i.e. &) is obligatory to get a pointer to member function. For non-member function it's optional because of function-to-pointer implicit conversion.

A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:

Upvotes: 4

Related Questions