Andrew Tomazos
Andrew Tomazos

Reputation: 68638

Why can't you get pointer-to-member from unqualified member function name in C++11?

The following code:

struct X
{
    void f() {}

    void g()
    {
        auto h = &f;
    }
};

results in:

error: ISO C++ forbids taking the address of an unqualified
or parenthesized non-static member function to form a pointer
to member function.  Say ‘&X::f’

My question is, why is this not allowed and forbidden by the standard? It would be more convenient as a user to refer to it unqualified, so I assume there is some other rationale (safety? an ambiguity? ease of compiler implementation?) for the requirement?

Upvotes: 10

Views: 3603

Answers (2)

kfsone
kfsone

Reputation: 24249

You're taking the address of a member function, not a function, and that means you will have to call it differently, too.

struct X
{
    void f() {}

    void g()
    {
        auto h = &X::f;
        h();
    }
};

Produces:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘h (...)’, e.g. ‘(... ->* h) (...)’

Upvotes: 0

Balog Pal
Balog Pal

Reputation: 17163

pointer-to-member is rare enough to allow special treatment and not necessarily the most economic one. It was decided that the only accepted form is the one quoted in the error message. That form does not clash with anything else under any circumstances. And prevents ambiguity of more lax forms were allowed.

Practice shows little awareness of PTMFs, and the fact they fundamentally differ from functions. f or &f is likely a request for a normal function. One that can't be served for a nonstatic member. And those who actually mean PTMF say so adding the &X:: part.

Upvotes: 7

Related Questions