I have the following code:
struct M {
friend void f() {}
M() {
f(); // error: 'f' was not declared in this scope
}
};
int main() {
M m;
}
Both g++4.8 and clang3.4 fail to compile it, because f
is not visible inside M
, or so they say.
However, the Standard gives an example of a similar code
class M {
friend void f() { } // definition of global f, a friend of M,
// not the definition of a member function
};
and says that
A
friend
function defined in a class is in the (lexical) scope of the class in which it is defined.
(ISO/IEC 14882:2011 11.3 Friends [class.friend] p6, p7)
From this I can't understand how compiler can't find f
which is defined in same class where it's used.
It's kinda unlikely that both compilers have the same bug.
So, what did I miss?
The friend declaration states that a function called f
in the surrounding namespace is a friend of the class; but it does not introduce the name f
into the namespace. It's not available (except by argument-dependent lookup) until it's been declared in the namespace.
The relevant rule is C++11 7.3.1.2/3:
If a
friend
declaration in a non-local 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 or by qualified lookup until a matching declaration is provided in that namespace scope.