Scope of `using namespace` within another namespace

时间:2015-10-06 08:55:39

标签: c++ scope using-directives

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.

3 个答案:

答案 0 :(得分:5)

标准说(7.3.4 / 2)

  

一个   使用指示符   指定指定命名空间中的名称可以在其中使用的范围内   使用指示符   出现之后   使用指示符   

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*/ |
}                  |
}                 /

因此使用此指令可见的内容将在using namespace B行之后的A范围内随处可见。当然,如果你在头文件中这样做,所有的东西都会在你包含那个头文件的地方可见,所以你不应该在头文件的任何地方使用“using namespace ...”。

答案 1 :(得分:1)

  

命名空间块中的using语句对同一名称空间的所有块都有效吗?

当翻译单元中显示using指令(包括在内)时,是。

由此产生的封闭命名空间污染是您不将这些语句放在头文件中的原因,或者通常/在命名空间范围内避免使用它们。

供参考:

答案 2 :(得分:0)

我认为根据命名空间理论,你的问题是正确的,因为这个机制用于将库定义的名称推入单个 地方,它有助于避免无意中的名称冲突