1

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:

  1. Should namespaces be used to organize code or simply to avoid name clashes? and if so

  2. 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;
}
Community
  • 1
  • 1
dudu
  • 675
  • 6
  • 15
  • Aside from ADL I can't think of any. Of course, from a personal style point of view I wouldn't personally nest so many namespaces. – Rapptz Jul 27 '13 at 04:34
  • 1
    @Johnsyweb. Opps, you're right. In those cases should I delete the post or simply edit it? – dudu Jul 27 '13 at 04:57
  • @dudu, Do not delete it. Let it be as it is. If moderator feels the need, your question will be closed. But still the heading of your question is searchable in Google – iammilind Jul 27 '13 at 05:03
  • If you bring too many things into other namespaces, you may end up with the problem you tried to avoid (name clashes). – Neil Kirk Jul 27 '13 at 06:22

0 Answers0