Declaring ambiguity using declaration

Take a 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 does not compile since fn() ambiguous in int z = fn();

If I put using and z in the namespace (delete two // ), the code compiles. Why is this? What is special about the global namespace?

+7
c ++
source share
1 answer

See [namespace.udir] / 2

The using directive states that names in the nomenclature namespace can be used in the area in which the using directive appears after the use directive. When searching for an unqualified name (3.4.1), names appear as if they were declared in the nearest spanning namespace, which contains both a pointer directive and a nominated namespace.

Thus, when you have an Ns namespace, the directives using namespace A; and using namespace B map A::fn and B::fn to the global namespace, while using A::fn; does fn in Ns . The last declaration wins while searching for a name.

+7
source share

All Articles