Consider a class inside a namespace. The definition of the class declares a friend function.
namespace Foo
{
class Bar
{
friend void baz();
The first piece of code should compile:
namespace A {
struct B {
friend void foo();
};
}
void A::foo() {}
Although it that particular function cannot be used unless you also provide a declaration at namespace level. The reason is that friend declarations are only seen through Argument Dependent Lookup (ADL), but foo
does not depend on A::B
, and thus the compiler will never look inside that type.
Why do I have to declare baz() twice?
Because the friend declaration doesn't provide a usable declaration of the function in the namespace. It declares that, if that function is declared in that namespace, it will be a friend; and if you were to define a friend function inside a class, then it would be available via argument-dependent lookup (but not otherwise) as if it were declared in the namespace.
Why is the definition otherwise only legal inside a namespace, and illegal with the scope resolution operator?
Because it hasn't been (properly) declared in the namespace, and a function can only be defined outside its namespace (with scope resolution) if it has been declared.
Why does the flag eliminate the error?
Because the flag causes the friend declaration to act as a declaration in the namespace. This is for compatibility with ancient dialects of C++ (and, apparently, some modern compilers) in which this was the standard behaviour.