Green Tree Green Tree - 4 years ago 134
C++ Question

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download