geza
geza

Reputation: 29942

Resolving ambiguity with using declaration

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?

Upvotes: 7

Views: 238

Answers (1)

Brian Bi
Brian Bi

Reputation: 119069

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.

Upvotes: 8

Related Questions