In C++, what is a "namespace alias"?

More on this topic http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-1-of-n

It is all about choosing an alias for a looong namespace name, such as:

namespace SHORT = NamespaceFirst::NameSpaceNested::Meow

Then later, you can typedef

typedef SHORT::mytype

instead of

typedef NamespaceFirst::NameSpaceNested::Meow::mytype

This syntax only works for namespaces, cannot include classes, types after the namespace NAME =


A namespace alias is a convenient way of referring to a long namespace name by a different, shorter name.

As an example, say you wanted to use the numeric vectors from Boost's uBLAS without a using namespace directive. Stating the full namespace every time is cumbersome:

boost::numeric::ublas::vector<double> v;

Instead, you can define an alias for boost::numeric::ublas -- say we want to abbreviate this to just ublas:

namespace ublas = boost::numeric::ublas;


ublas::vector<double> v;

Quite simply, the #define won't work.

namespace Mine { class MyClass { public: int i; }; }
namespace His = Mine;
namespace Yours { class Mine: public His::MyClass { void f() { i = 1; } }; }

Compiles fine. Lets you work around namespace/class name collisions.

namespace Nope { class Oops { public: int j; }; }
#define Hmm Nope
namespace Drat { class Nope: public Hmm::Oops { void f () { j = 1; } }; }

On the last line, "Hmm:Oops" is a compile error. The pre-processor changes it to Nope::Oops, but Nope is already a class name.

Tags:

C++

Namespaces