Everything about namespaces

Posted on: 24/09/2009

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 without the using keyword, 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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 27 other followers


%d bloggers like this: