c ++通过"using"在另一个未封闭的命名空间中定义class

c++ defining class in another, not enclosing, namespace via "using"

g++、icc 和 clang 接受以下代码:

namespace ns { struct A ; }
namespace ns1 // note : not enclosing namespace
{ 
    using namespace ns ;
    struct A { } ;
}  

这是符合标准的有效代码吗?


[namespace.qual]#7: ... However, in such namespace member declarations, the nested-name-specifier may rely on using-directives to implicitly provide the initial part of the nested-name-specifier.

如相关 answer

中所述

you may omit the initial part of the nested-name-specifier, but not any intermediate part.

(我从哪里知道它 can/must 是在封闭的命名空间中完成的,我不记得了。)

代码符合要求,但可能无法达到您的预期。

namespace ns 
{ 
    struct A ;      // declaration of ns::A
}
namespace ns1
{ 
    using namespace ns ;
    struct A { } ;  // definition of ns1::A, which has nothing to do with ns::A
} 

注意命名空间内的任何声明都成为该命名空间的成员,因此 ns::Ans1::A 是两个不相关的 struct

代码编译很好,但我同意@songyuangyao 的回答,同时注意阴影。

例如,

namespace ns 
{ 
   struct A ;
  /* Calling A inside this scope will definitely refer to struct A defined in
     this(ns) namespace, and everytime you want to access struct A of ns1, 
     you need to call it via ns1::A otherwise it will refer to ns::A (which is defined in 
     this namespace.
  */
}    
namespace ns1
{ 
   using namespace ns ;
   struct A { } ;
}