Scope of friend function in GCC
According to the standard:
A friend function defined in a class is in the (lexical) scope of the class in which it is defined.
Then why the heck isn't working (multiple versions of GCC tested)?
#include <iostream>
using namespace std;
class A
{
friend void function() { cout << "text" << endl; };
};
// void function();
int main()
{
function();
return 0;
}
Exposing the declaration, of course, solves the problem.
Edit (gcc output):
(xterm) $ g++ -ansi -pedantic -Wall -Wextra test.cpp
test.cpp: In function βint main()β:
test.cpp:13:11: error: βfunctionβ was not declared in this scope
source to share
The quote means the following works: the code is in the lexical scope of the class, so the unqualified name lookup will behave on purpose
class A
{
typedef int type;
friend void function() {
type foo; /* type is visible */
};
};
If you have defined a "function" in the scope of a namespace then the "type" will not be visible - you will need to say "A :: type". That's why the next sentence says, "A friend function defined outside of a class is not." An unqualified name lookup for class definition is defined as
A name lookup for a name used in a friend function definition (11.4) defined on a string in a friend grant class is done as described for lookup in member function definitions. If a friend function is not defined in a class that provides friendship, a name lookup in a friend function definition must be performed as described for a namespace member function definition lookup.
So the text you quoted isn't actually required to be normative - the unqualified name lookup specification already covers it.
source to share