EDIT: This does not really seem a duplicate to me since this question in broader in scope (how to use it). Anyways, the answer to my question does turn out to be there in paercebal's answer and is namespace composition. Another related source in SO is this other question.
I've been trying to modularize my code using namespaces. Anon's answer to a question on nested namespaces got me wondering whether they should be used for design instead of simply avoiding name clashes.
I feel like namespaces (occasionally nested ones) are useful to organize the code, but sure things like world::europe::spain::madrid
become cumbersome to use. Therefore, from an API point of view, having most code in the same namespace (just like the std
library) works best.
My question is then two fold:
Should namespaces be used to organize code or simply to avoid name clashes? and if so
How to have a "complex" namespace structure while keeping the API clean?
Regarding question 2, I've been using the following strategy:
(1) having some code with its own namespace
//mathlib.h
namespace mathlib {
int sum( int a, int b ) {
return a + b;
}
}
(2) and bring it into another namespace
//otherlib.h
#include <iostream>
#include "mathlib.h"
namespace otherlib {
using namespace mathlib; // lookup stuff inside mathlib
void print(int n) {
std::cout << "the int is " << n << "!";
}
}
(3) So I can actually call sum
as it were under the otherlib
namespace.
#include "otherlib.h"
int main(){
auto myint = otherlib::sum(1, 2);
otherlib::print(myint);
return 0;
}