Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving ambiguity with using declaration

Tags:

c++

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?

like image 238
geza Avatar asked Jul 03 '17 22:07

geza


1 Answers

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.

like image 77
Brian Bi Avatar answered Oct 03 '22 23:10

Brian Bi