Look at this snippet:
namespace A {
int fn();
}
namespace B {
int fn();
}
// namespace Ns {
using namespace A;
using namespace B;
using A::fn;
int z = fn();
// }
This code doesn't compile, as fn()
is ambiguous at int z = fn();
If I put using
's and z
into a namespace (remove the two //
), the code compiles. Why is that? What is special about the global namespace?
See [namespace.udir]/2
A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace.
Thus, when you have the namespace Ns
, the directives using namespace A;
and using namespace B
make A::fn
and B::fn
appear in the global namespace, whereas using A::fn;
makes fn
appear in Ns
. The latter declaration "wins" during name lookup.
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