Pointer to a static member function in a structure

struct X { int f(int); static int f(long); }; int (X::*p1)(int) = &X::f; // OK int (*p2)(int) = &X::f; // error: mismatch int (*p3)(long) = &X::f; // OK int (X::*p4)(long) = &X::f; // error: mismatch int (X::*p5)(int) = &(X::f); // error: wrong syntax for pointer to member int (*p6)(long) = &(X::f); // OK 

I think p1 and p5 are the same case. Why is p5 wrong?

+5
source share
2 answers

The standard definition of the built-in operator & in C ++ means that only if the & parameter is an identifier with qualifications, which means something like Class::Member , then & leads to an element, Brackets are that it is no longer an identifier with qualifications, so it tries to parse X::f directly, which is illegal in this context: you assign int (*)(long) to int (X::*)(int) .

The distinction between the two cases eliminates the ambiguity. Let's say that you have:

 struct X { int m; }; struct Y { int m; }; struct Z : X, Y { void F(); }; void Z::F() { int X::*p1 = &X::m; int *p2 = &(X::m); } 

Here &X::m is a member pointer, while &(X::m) is a regular int pointer, using the X:: qualification to resolve the ambiguity between X m and Y m .

+2
source

Because the standard says so. From N3936:

5.3.1 Unary operators

  1. A pointer to a member is formed only when explicit and used, and its operand is an identifier with qualifications, not enclosed in parentheses . [Note: that is, the expression & (qualified-id), where the identifier is enclosed in parentheses, does not form an expression of type "pointer" to the member. "And it doesn’t have an identifier, because there is no implied conversion from a qualified identifier for a non-static member function to a type of a pointer to a member function, because there is a value l of the type of the function to the type of a pointer to a function (4.3). Also no & unqualified-id - pointer to an element, even within an unqualified class. - final note]
+5
source

Source: https://habr.com/ru/post/1264851/


All Articles