In the current draft of the C++ standard (march 2019) [class.friend] p.6 states (emphasis mine):
A function can be defined in a friend declaration of a class if and only if the class is a non-local class ([class.local]), the function name is unqualified, and the function has namespace scope. [...]
What does "the function has namespace scope" mean?
The only situation that I could come up with in which the function does not have namespace scope is the following:
struct A
{
static void f();
struct B
{
friend void f() {};
};
};
However both clang and gcc do not associate the friend definition inside B
to the static method inside A
, but to a function that belongs to the global namespace.
Are there other situations I am missing?
I think that you have actually answered your own question, but without realizing it.
"The function has namespace scope" means that it is part of a namespace, not part of a class or struct. So the function A::B::f() doesn't exist. And it doesn't refer to A::f() either. Instead, the function you have defined as the friend is actually the function ::f(), since that is the namespace that it resides in (the global namespace).
I suspect (but have not tried), that if you wrap all of this in a namespace, then the f() you are defining would be a part of that namespace. So, for example,
namespace ns {
struct A
{
static void f();
struct B
{
friend void f() {};
};
};
}
would define the friend function as the function ns::f().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With