33

I've been doing C++ for a long time now but I just faced a question this morning to which I couldn't give an answer: "Is it possible to create aliases for namespaces in C++ ?"

Let me give an example. Let's say I had the following header:

namespace old
{
  class SomeClass {};
}

Which, for unspecified reasons had to become:

namespace _new
{
  namespace nested
  {
    class SomeClass {}; // SomeClass hasn't changed
  }
}

Now if I have an old code base which refers to SomeClass, I can quickly (and dirtily) "fix" the change by adding:

namespace old
{
  typedef _new::nested::SomeClass SomeClass;
}

But is there a way to import everything from _new::nested into old without having to typedef explicitely every type ?

Something similar to Python import * from ....

Thank you.

ereOn
  • 53,676
  • 39
  • 161
  • 238

2 Answers2

64
using namespace new::nested;

Example at Ideone.

Or if you actually want a real alias:

namespace on = one::nested;

Example at Ideone.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • 7
    The second one is much better than the first one... the first one does not create an alias, but rather brings the symbols from the other namespace and that might end up in name clashes or unwanted results (if a function overload in the `nested` namespace is a better match than an overload in the current namespace, it will suddenly change its pick) – David Rodríguez - dribeas May 24 '11 at 10:44
  • @David: Yes, but it seems to solve the problem the OP seems to have. :) – Xeo May 24 '11 at 10:45
33

This:

namespace old = newns::nested;

would seem to be what you want.