Search code examples
c++namespacesboilerplate

Is it possible to avoid namespace boilerplate in a header file?


I have some helper classes that I don't want in the global namespace, so I want to put them in their own namespace. For example:

// Widget.h
namespace MyHelpers {
    class Helper { ... };
}

class Foo {
    void bar(MyHelpers::Helper *helper);
}

// Widget.cpp
using namespace MyHelpers;

Foo::bar(Helper *helper) { ... }

In in the .cpp file, Helper can be referenced directly, while in the .h file, it is referenced using the namespace. Is it possible to have the header file lose the "MyHelpers::" boilerplate, while still reserving MyHelpers from the global namespace?


Solution

  • If you have many of these, create a type shortcut inside the using class declaration:

    class Foo {
        ...
        typedef MyHelpers::Helper Helper;
        ...
        void bar(Helper *helper);
        ...
    };