Below is the sample code
#include <iostream>
using namespace std;
namespace A {
void f() { cout << "a" << endl; }
}
namespace B {
void f() { cout << "b" << endl; }
}
namespace C {
using namespace A;
using namespace B;
using A::f;
}
namespace D {
using A::f;
using namespace A;
using namespace B;
}
int main()
{
C::f();
D::f();
}
This prints "a" twice when I try in Visual Studio 2015, is this behavior defined by standard or is this implementation specific?
It's defined by the standard (things like this always are). The key thing to realize, is that your various using namespace
lines do not have any effect on your program.
using namespace Foo
is a "using directive", which affects name lookup which is performed by code within the scope. That is, if some later function in your namespace C {}
block tried to find some object named foo
, A
and B
would be among the places that the compiler would search to find a foo
. In contrast, it wouldn't change where the compiler would look if later code referred to C::foo
. The order of two consecutive using namespace
s in a single block is immaterial, since each one has full effect until the end of the block.
The reason you're able to find an f
in C
or D
is the "using declaration" using A::f
. A using-declaration, unlike a using-directive, has the effect of injecting a name into a scope, such that other code can refer to the name as being within that scope.