19

It's considered bad practice to employ using namespace in C++ headers. Is it similarly a bad idea to use namespace aliasing in a header, and each implementation file should declare the aliases it wishes to use?

Since headers are the places you tend to use fully specified names (since we don't use namespaces in headers), aliases would be useful but they would still propagate though your source when #included.

What is the best practice here? And what is the scope of a namespace alias?

Community
  • 1
  • 1
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 2
    If you're doing everything in your own namespace then it's fine, no? I think it's only problematic when you do it at global scope. – Pubby Mar 22 '13 at 14:45

2 Answers2

10

If you put a namespace alias into your header this alias will become part of your (public) API.

Sometimes this technique is used to do ABI compatible versioning (or at least to make breakage visible) like this:

namespace lib_v1 { ... }
namespace lib_v2 { ... }
namespace lib = lib_v2;

or more commonly:

namespace lib {
   namespace v1 {}
   namespace v2 {}
   using namespace v2;
}

On the other hand if you do it just to save some typing it is probably not such a good idea. (Still much better than using a using directive)

Fabio Fracassi
  • 3,791
  • 1
  • 18
  • 17
3

I do it with unnamed namespaces this way:

#include <whatyouneed>
...
namespace {

typedef ...
using ..
namespace x = ...

// anything you need in header but shouldn't be linked with original name

}

// normal interface
class a: public x::...
podshumok
  • 1,649
  • 16
  • 20
  • I've not seem that paradigm before. I'll wait on other people to weigh in before I decide if I want to use it :) – Mr. Boy Mar 22 '13 at 15:01
  • see also http://stackoverflow.com/questions/357404/why-are-unnamed-namespaces-used-and-what-are-their-benefits – podshumok Mar 22 '13 at 15:12
  • 3
    that is about using nameless namespaces in implementation files, isn't that very different to using them in header files? Anything you put in that namespace is still visible to files which `#include` it (in my test anyway). – Mr. Boy Mar 22 '13 at 15:32
  • 5
    John is right here. Unnamed namespaces do not buy you anything here, worse, each TU will now have its own unique name for those entities. – Fabio Fracassi Mar 22 '13 at 15:32
  • 1
    There is a few issues here, yes. I just mean that if you have problems with global definitions in your header file and you don't want to move all implementation to the source and write full namespace spec everywhere, then you should look at unnamed namespaces. If this solution is unacceptable (usually it is) than you have to write full specs (boost::filesystem::etc..) or try to make good of propagation of alias names through #include – podshumok Mar 22 '13 at 16:36