From section 7.3.4.2 of the c++11 standard:
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. [
Note: In this context, “contains” means “contains directly or
indirectly”. —end note ]
What do the second and third sentences mean exactly? Please give example.
Here is the code I am attempting to understand:
namespace A
{
int i = 7;
}
namespace B
{
using namespace A;
int i = i + 11;
}
int main(int argc, char * argv[])
{
std::cout << A::i << " " << B::i << std::endl;
return 0;
}
It print “7 7” and not “7 18” as I would expect.
Sorry for the typo, the program actually prints “7 11”.
Eliminating the undefined behaviour:
The meaning of the standard is that at the line
the name
iappears in the “nearest enclosing namespace which contains both the using-directive and the nominated namespace“; the using-directive appears innamespace Bwhile the nominated namespace isnamespace A; the nearest enclosing namespace is the global namespace, soiappears as::i. This means that if a nameiis already present in the global namespace the code is ambiguous.For a more complex example:
At the line
int j = i,iappears in the nearest enclosing namespace of the using-directive (i.e.,A::D) and the nominated namespace (A::B::C), which isA. So, withinA::Dafter the using-directive, and so also withinA::D::E, the unqualified nameican refer toA::B::C::iappearing asA::i, shadowing any::i, conflicting with anyA::i, and being shadowed by anyA::D::iorA::D::E::i(withinA::D::E):Note that just because the name appears as
A::iduring unqualified name lookup, that does not mean that it actually is there; the qualified nameA::iwill continue to refer only to an actual nameA::i(if any exists).