I am trying to declare a function within unnamed namespace as a friend of a class inside a named namespace but it fails.
I am using "gcc (GCC) 13.1.1 20230429"
Please consider the code below (all within a same file):
namespace {
void afunc(auto&);
}
namespace aspace{
class aclass{
int a;
friend void afunc(auto&);
};
}
namespace {
void afunc(auto& ref){
ref.a = 12;
}
void bfunc(aspace::aclass& ref) {
afunc(ref);
}
}
Which gives this error:
error: call of overloaded ‘afunc(aspace::aclass&)’ is ambiguous
note: candidate: ‘void {anonymous}::afunc(auto:16&) [with auto:16 = aspace::aclass]’
note: candidate: ‘void aspace::afunc(auto:17&) [with auto:17 = aclass]’
the first note: candidate: ‘void {anonymous}::afunc(auto:16&) [with auto:16 = aspace::aclass]’
refers to the definition of the afunc
and interestingly the later note: candidate: ‘void aspace::afunc(auto:17&) [with auto:17 = aclass]’
refers to the friend declaration inside aclass
(same line number)!
If I name the unnamed namespace, code will compile flawlessly:
namespace bspace{
void afunc(auto&);
}
namespace aspace{
class aclass{
int a;
friend void bspace::afunc(auto&);
};
}
namespace bspace{
void afunc(auto& ref){
ref.a = 12;
}
void bfunc(aspace::aclass& ref) {
afunc(ref);
}
}
I tried using ::afunc
instead of afunc
in different places within the code with no success. Providing the definition of the afunc
instead declaring it did not help either.
After reading similar questions like Is it possible to friend a class in an anonymous namespace in C++? and GCC doesn't like to make friends with anonymous namespace forward declarations, but MSVC does. What? , I am confused.
Is it impossible/forbidden to declare any thing inside unnamed namespaces as friend or is this just shortcoming of GCC?
If the later case is true, is there any workaround?