class A {
friend void f() {}
};
// void f() {} // compile error: redifinition of 'void f()'
int main() {
f(); // compile error: 'f' is not declared in this scope
}
As you can see in the above example, if f
is called in A
's enclosing namespace scope, the compiler just can't find f
, which gives me the idea that f
is not in this scope. But when an out-of-calss definition of a function with the same signature is added, the compiler issues an error of function redefinition, which gives me the opposite idea that f
is actually in this scope.
So, I'm puzzled which scope an in-class-defined friend function belongs to.
It's in the namespace containing the class.
However, if it's only declared in the class, then it's only available by argument-dependent lookup. So this would work, with the argument type A
finding f
in the surrounding namespace:
class A {
friend void f(A) {}
};
int main() {
f(A()); // OK: uses ADL
::f(A()); // Error: doesn't use ADL, and can't find the name without it
}
This is often used for overloaded operators, which can only be found by ADL anyway.
Your version would work if you declared, rather than redefined, the function at namespace scope.
void 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