Friend Functions and Static Data Elements

How is an unqualified name searched for names used in the body of a friend function? Consider the following code:

#include <iostream> void foo(); class A { friend void foo(){ std::cout << a << std::endl; } static int a; }; int A::a = 10; int main(){ foo(); } 

Demo

Standard states in N4296::7.3.1.2/3 [namespace.memdef] :

If declaring a friend in a non-local class first declares a class, function, template, or function template of which a friend of the innermost enclosing namespace is a member.

So, I expected that searching for an unqualified name would not find A::a , but he did. I intentionally place an A::a declaration after defining a friend function in the hope that it will not be found. What is the actual rule for finding an unqualified friend name?

+6
source share
1 answer

The answer was pretty simple:

N4296::3.4.1/8 [basic.lookup.unqual] :

For members of class X, the name used in the body member function , in the default argument, in the exception description, in the sliding or equal-initializer of the non-static data element (9.2) or in the definition of the class member outside the definition of X, after declaring the declarator-id31, is declared in one of the following ways:

[...]

(8.2) - must be a member of class X or be a member of base class X (10.2),

[...]

N4296::3.4.1/9 [basic.lookup.unqual] :

The search for the name for the name used in the friend function definition (11.3) defined inline in the class that provides friendships continues as described for the search in member function definitions .

What is it.

UPD:

Attachment is important here. Therefore, the friend function, defined outside the class definition, cannot directly use the static members of the class. For example, the following code causes a compile-time error:

 #include <iostream> class A { static int a; friend void foo(); }; int A::a = 10; void foo(){ std::cout << a << std::endl; } int main(){ foo(); } 

Demo

+4
source

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


All Articles