Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 480
Andrew Tomazos Avatar asked Jun 02 '13 02:06

Andrew Tomazos


People also ask

How many different ways are possible to pass a pointer to a function call?

There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.

How do you get a pointer to member function?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .

How do you access members of the class inside a member function?

7. How to access members of the class inside a member function? Explanation: The members of a class can be used directly inside a member function. We can use this pointer when there is a conflict between data members of class and arguments/local function variable names.

Can we call member function using this pointer from constructor?

the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.


1 Answers

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.

like image 149
Balog Pal Avatar answered Nov 05 '22 09:11

Balog Pal