无意中看到C++11中的新特性inline namespace, 先附上官方的解释
Inline namespace
The inline namespace mechanism is intended to support library evolution by providing a mechanism that support a form of versioning. Consider:
// file V99.h: inline namespace V99 { void f(int); // does something better than the V98 version void f(double); // new feature // ... } // file V98.h: namespace V98 { void f(int); // does something // ... } // file Mine.h: namespace Mine { #include "V99.h" #include "V98.h" }
We here have a namespace Mine with both the latest release (V99) and the previous one (V98). If you want to be specific, you can:
#include "Mine.h" using namespace Mine; // ... V98::f(1); // old version V99::f(1); // new version f(1); // default version
The point is that the inline specifier makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace.
This is a very ``static'' and implementer-oriented facility in that the inline specifier has to be placed by the designer of the namespaces -- thus making the choice for all users. It is not possible for a user of Mine to say ``I want the default to be V98 rather than V99.''
上面的说法大概可以这么理解,当你需要管理多个版本的类库的时候,可以用inline修饰namespace,来达到指定默认版本的目的,例如在以上的例子中 inline namespace V99 在编译的过程中会直接将里面的代码展开,就像如下的表示方式:
namespace Mine { void f(int); // does something better than the V98 version void f(double); // new feature // ... // file V98.h: namespace V98 { void f(int); // does something // ... } }
所以V99里面的方法就相当于默认的方法一样,当我们不指定命名空间直接调用 f(1); 时,就是默认调用V99里面的f();而且这个默认是我们无法去改变的,也就是说我们想调用V98里面的f(),就必须写成这样V98::f(1); 。