Everything about namespaces

I’ll assume you are already familiar with the concept of namespaces, and the using keyword. So let me try and introduce some of the less common features of the namespace mechanism.

Anonymous namespaces

It is possible to define an anonymous namespace, like so:

namespace {
    class Helper {};

int main () {
    Helper h;
    return 0;

The contents of an anonymous namespace are considered to be local to the file they have been defined in - much like the static keyword from c. Another thing worth mentioning is that, inside the anonymous namespace you are bound to have no conflicts with global names, as anything defined inside the same namespace has precedence.

Namespace aliasing (or, renaming namespaces)

Suppose you are using pretty lengthy names for namespaces, or just have many nested small ones. Having a way to shorten the access to their contents while avoiding using directives, can be pretty useful. Here is how you can achieve just that:

namespace A {
    namespace Very {
        namespace Long {
            namespace Namespace {
                int f () { return 0; }

int main () {
    namespace N = A::Very::Long::Namespace;
    return N::f();

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>