Should C++ namespace aliasing be used in header files?

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?


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 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)


我这样用无名命名空间来做:

#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::...
链接地址: http://www.djcxy.com/p/70178.html

上一篇: 以d结尾的cfspreadsheet字母数字值

下一篇: 应该在头文件中使用C ++名称空间别名?