aga
aga

Reputation: 357

Discontigous nested namespaces

I have a project in which Nested namespace is required but these namespace will be spread over multiple headers.

//BaseDeclaration.h
namespace Base_NS
{
namespace Element_NS{};
namespace StockItem_NS{};
}

This is the structure of my Base Header.

Now I want to use Element_NS in Element.h or StockItem_NS in StockItem.h What is the best way to use these discontiguous nested namespaces.

//Element.h
namespace Base_NS{
namespace Element_NS{
int data;
}
}

or 

namespace Element_NS{
int data;
}

Or is there any other appropriate of handling this type of cases.

Thanks

Upvotes: 1

Views: 228

Answers (2)

brainstream
brainstream

Reputation: 461

First of all, you should not declare empty namespaces in the BaseDeclaration.h file.

There are two approaches to write code in shared namespaces. First is a simple one, you just write namespaces each time when it necessary, like you mentioned above.

namespace Base_NS {
namespace Element_NS {
    int data;
}
}

Or you can define macros (the BaseDeclaration.h file is good place for it)

#define BEGIN_ELEMENT_NS 
    namespace Base_NS { \
    namespace Element_NS {

#define END_ELEMENT_NS }}

And use it instead

BEGIN_ELEMENT_NS
    int data;
END_ELEMENT_NS

Second approach is used in some libraries like Qt and Boost. After all, second approach allows to avoid typos in namespace names.

Upvotes: 1

Richard Hodges
Richard Hodges

Reputation: 69854

Until c++17:

namespace Base_NS{
  namespace Element_NS{
    int data;
  }
}

Since c++17:

namespace Base_NS::Element_NS {
  int data;
}

Upvotes: 4

Related Questions