3

g++, icc and clang accept following code :

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

is this a valid code due to standard.?


[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.

as noted in related answer,

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

(from where i got that it can/must be done in enclosing namespace i do not remember.)

Community
  • 1
  • 1
Volodymyr Boiko
  • 1,533
  • 15
  • 29

2 Answers2

5

The code complies, but might not do what you expected.

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
} 

Note any declarations inside the namespace become the members of that namespace, so ns::A and ns1::A are two irrelevant structs.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

The code compiles well but I agree with @songyuangyao's answer, also beware of shadowing.

For instance,

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 { } ;
} 
Onur A.
  • 3,007
  • 3
  • 22
  • 37