§7.3.1.2/3 in the C++11 Standard (emphasis are mine):
Every name first declared in a namespace is a member of that namespace. If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). If a friend function is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments (3.4.2). If the name in a friend declaration is neither qualified nor a template-id and the declaration is a function or an elaborated-type-specifier, the lookup to determine whether the entity has been previously declared shall not consider any scopes outside the innermost enclosing namespace. [ Note: The other forms of friend declarations cannot declare a new member of the innermost enclosing namespace and thus follow the usual lookup rules.
Example:
// Assume f and g have not yet been defined. void h(int); template <class T> void f2(T); namespace A { class X { friend void f(X); // A::f(X) is a friend class Y { friend void g(); // A::g is a friend friend void h(int); // A::h is a friend // ::h not considered friend void f2<>(int); // ::f2<>(int) is a friend }; }; // A::f, A::g and A::h are not visible here X x; void g() { f(x); } // definition of A::g void f(X) { /* ... */} // definition of A::f void h(int) { /* ... */ } // definition of A::h // A::f, A::g and A::h are visible here and known to be friends } using A::x; void h() { A::f(x); A::X::f(x); // error: f is not a member of A::X A::X::Y::g(); // error: g is not a member of A::X::Y }
Unless I'm missing something, I don't understand the need for the words first above. As far as I can see, you can't have more than one declaration of any entity in a namespace, nor more than one declaration of a friend function in a class.
Also, what is the relevance of the comment "Assume f and g have yet not been defined" in the Example? It really doesn't matter if these functions are declared before the definition of the namespace A. They'll necessarily belong to the global namespace and they'll have nothing to do with the functions declared inside the namespace A.
Edit:
The fact that one can have repeated declarations of the same function, or a declaration and a definition of a function in a namespace, doesn't invalidate my observation that the use of the words first in §7.3.1.2/3 are not necessary.
Edit1
I've just found another error. The comment ::f2<>(int) is a friend
is incorrect. Not only there is no definition of the template function f2(T)
in namespace A, but more important, the declaration template <class T> void f2(T);
must be inside A, otherwise the function f2<>(int)
will not be a friend of the class A::X::Y
.