6
votes

How is unqualified name lookup being performed for names using within the friend's function body? Let's 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

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

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

So, I expected unqualified name lookup didn't find A::a, but it did. I deliberately put the A::a declaration after the friend's function definition in hope it wouldn't be found. What's the actual rule for the friend's unqualified name lookup?

1
Neat question; I'm assuming it has to do with the fact it's a friend, so it's able to access in-scope members of A while still be placed in the direct parent's scope. I've never considered this before; interesting find.Qix - MONICA WAS MISTREATED
There is no relationship between the friend declaration and the static member variable. I don't know why you think they are related.R Sahu
@RSahu I just asked about unqualified name lookup for stattic data members beacuse We can't use non-ststaic members within friends' function bod directly.user2953119
@DmitryFucintv, I understand your question now. Thanks for clarifying.R Sahu
@RSahu Since you undersntand my question, maybe you probaly know an answer?user2953119

1 Answers

4
votes

The answer was quite simple:

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

For the members of a class X, a name used in a member function body, in a default argument, in an exceptionspecification, in the brace-or-equal-initializer of a non-static data member (9.2), or in the definition of a class member outside of the definition of X, following the member’s declarator-id31, shall be declared in one of the following ways:

[...]

(8.2) — shall be a member of class X or be a member of a base class of X (10.2),

[...]

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

Name lookup for a name used in the definition of a friend function (11.3) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions.

That's it.

UPD:

Inlining is important here. That's why the friend function defined outside the class defintion cannot use static members of the class directly. For instance, the following code pritns 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