Search code examples
c++naming-conventionsnamespacesdeclarationprefix

How to mitigate class declaration being far from its owner namespace declaration in a file?


So, I've seen how useful namespaces can be to organize declarations into their respective groups, but now comes an issue with this.

The difference between making a library in C and a library in C++ is in C you must prefix your declarations with what they belong to, for example a library we'll dub MyMath might have a vector class, well the name might be MM_Vector.

In C++, you would have a namespace MyMath with a Vector class declared as a part of it.

Now the difference here is in C, just by going to the class declaration you immediately know how to use it. In C++, you would have to check which namespace a particular class belongs to (really only a problem in files where the declaration isn't near the namespace declaration, which can be common if there are constants and enumerations declared between the two). While I prefer using a namespace for organization, in my opinion this is still a valid argument as an annoyance.

What have people done to reduce this annoyance?


Solution

  • In chapter 8 of his book, Stroustrup recommends a style such as the following:

    MyMath.h

    namespace MyMath {
      class Vector;
    };
    

    Vector.h

    #include "MyMath.h"
    
    class MyMath::Vector {
      public:
      Vector();
      // ...
    };
    

    Vector.cc

    #include "Vector.h"
    
    MyMath::Vector::Vector() { /* ... */ }
    

    Limiting open namespace-declarations to declarations of their contents produces brief summaries. Fully-qualified definitions allow the compiler to catch typos.

    As applied to your concern, class declarations and definitions in this style make plain the parent namespace of each class—at the expense of what the Go folks call stuttering.