Consider the following example:
namespace X {
struct A { static const A aaa; };
const A A::aaa = {};
}
bool operator == (const X::A &a, const X::A &b) { return true; }
bool workaround (const X::A &a, const X::A &b) { return a == b; }
namespace Y {
using X::A;
struct B { const A & an_a() const { static A a; return a; } };
bool operator == (const B &a, const B &b) { return true; }
bool foo (const B &b) {
return b.an_a() == A::aaa;
//return workaround(b.an_a(), A::aaa);
}
}
int main () {}
This code fails to compile foo
because the ==
operator resolves the one in namespace Y
rather than the one in the global namespace.
.code.tio.cpp:17:25: error: invalid operands to binary expression ('const X::A' and 'const X::A') return b.an_a() == A::aaa; ~~~~~~~~ ^ ~~~~~~ .code.tio.cpp:14:10: note: candidate function not viable: no known conversion from 'const X::A' to 'const Y::B' for 1st argument bool operator == (const B &a, const B &b) { return true; } ^ 1 error generated.
I think I understand this is due to the way ADL has been defined for C++, which seems to explicitly exclude searching the global namespace if the class belongs to a namespace. But, it still seems counter-intuitive to me. Is there an explanation of why the global namespace could not be included in the set of namespaces to be searched for operator==
?