I know that I the scope of the using directive is limited to a block or a function when put inside. Then it will apply only to that scope. But if the block is a namespace
it apparantly applies through all blocks of the same namespace. Is that correct? At least, the following example suggests that: (http://ideone.com/K8dk7E)
namespace N1
{
struct Foo{};
}
namespace N2
{
using namespace N1;
Foo f;
}
namespace N2
{
Foo f2;
}
int main()
{
N2::f2;
}
I had expected Foo f2
to give an error, since Foo
should be unknown.
So my real question is, is a using
statement within a namespace block in effect for all blocks of the same namespace?
This is causing issues when all cpp files are included and compiled together, as it is polluting the other cpp files, that should not have the other namespace included (the one for which the using directive is put). So, in effect it may cause undesirable conflicts.
The standard says that (7.3.4/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 .
namespace A { \
int i = 9; | <-- namespace A scope.
} /
namespace B { \
using namespace A; | <-- namespace B scope. "i" is visible after
void bar() | the "using namespace" line.
{ |
i += 1; /*Ok*/ |
} |
} /
namespace B { \
void foo() |
{ | <-- still namespace B scope. "i" is still visible
i += 1; /*Ok*/ |
} |
} /
So stuff made visible with this using directive will be visible everywhere in A scope after the using namespace B
line. Of course, if you do this in a header file, all the stuff will be visible everywhere where you include that header file, so you should not really use "using namespace..." anywhere in the headers.
Is a
using
statement within a namespace block in effect for all blocks of the same namespace?
When the using directive is visible in the translation unit (is included), yes.
The resulting pollution of the enclosing namespace is why you don't put these statements in header files for example, or avoid them generally/in namespace scope.
For reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With