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

The following code:

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

leads to:

 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 it prohibited and prohibited by the standard? It would be more convenient if the user referred to him as unskilled, so I assume that there is some other justification (security? Uncertainty? Ease of compiler implementation?) For the requirement?

+7
source share
2 answers

a member pointer is rare enough to allow special handling and not necessarily the most economical one. It was decided that the only accepted form is the one indicated in the error message. This form under no circumstances collides with anything else. And the ambiguity of weaker forms was prevented.

Practice shows little awareness of PTMF and the fact that they are fundamentally different from functions. f or & f is probably a request for a normal function. One that cannot be filed for a non-static member. And those who really mean PTMF say so by adding & X :: part.

+6
source

You take the address of the member function, not the function, and this means that you also have to call it differently.

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

It produces:

  error: must use '. *' or '-> *' to call pointer-to-member function in 'h (...)', eg '(... -> * h) (...)'
0
source

All Articles