使用这个奇怪的名称空间技巧的原因是什么?

What can the reason be for making use of this strange namespace trick?

为什么我要写这样的东西并用东西填充// STUFF

// boost
namespace another_name {} namespace boost = another_name; namespace another_name {
// STUFF
}

这只是一个常规的 namespace definition followed by a namespace alias 定义别名前者。

// Namespace definition of namespace 'another_name'.
namespace another_name {} 

// Namespace alias definition, 'boost' aliases 'another_name'.
namespace boost = another_name; 

// Namespace (re-)definition: open up the declarative region
// described by the namespace 'another_name' to add e.g.
// function declarations, definitions and so on.
namespace another_name {
    void foo() {}
}

// foo() is available via the namespace alias 'boost'.

int main() { boost::foo(); }

但是请注意,定义别名 boost 可能会与实际名称空间冲突 boost

 namespace alias_name = ...

... alias_name must be a name not previously used ...

一旦你真正包含一个提升 header 你就会 运行 进入一个编译器错误:

// Existing namespace(s)
namespace boost {}
namespace another_name {} 

// Conflicing alias_name.
namespace boost = another_name;  // error: redefinition of 'boost

如果您在代码库中看到过这个特定示例,它可能是尝试提供一个内部的 seems-to-be boost(子集)实现,稍后可以通过删除别名和包括实际提升 headers,但无需更改使用 boost::.

明确限定实体的调用站点

例如,代码库的早期版本(在使用实际提升之前):

// internal_boost_like_impl.h
namespace internal_boost_like_impl {
    // Until-boost implementation of boost::mp11::mp_identity.
    namespace mp11 {
        template<typename T>
        struct mp_identity {
            using type = T;
        };
        
        template<typename T>
        using mp_identity_t = typename mp_identity<T>::type;
    }
}

// internal_boost.h
#include "internal_boost_like_impl.h"
namespace boost = internal_boost_like_impl;

// Code base looks to be using boost, but actually 
// uses implementations from internal_boost_like_impl.
#include "internal_boost.h"
template<typename T>
struct Foo { T t; };

template<typename T>
void addToFoo(Foo<T>& foo,  
              boost::mp11::mp_identity_t<T> val) { foo.t += val; }
                         // ^^^^^^^^^^^^^ T in non-deduced context.

后面internal_boost.h修改成

// internal_boost.h
#include "boost/mpl/identity.hpp"

这种方法可以说可以更容易地促进变体(比如一个产品变体,其中第 3 方库可能由于安全关键问题而无法使用)但它也可能会使开发人员感到困惑,并且可以说更好的方法是提供一个独特的为不同的 variants/versions 简单地设置不同值的别名(而不是提供一个名为 as 的别名,然后完全由实际的 well-known 名称空间(例如 boost)替换)。