Enr*_*lis -1 c++ alias namespaces namespace-alias
为什么我要写这样的东西并填满// STUFF
东西?
// boost
namespace another_name {} namespace boost = another_name; namespace another_name {
// STUFF
}
Run Code Online (Sandbox Code Playgroud)
这只是一个常规命名空间定义,后跟一个命名空间别名定义,作为前者的别名。
// 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(); }
Run Code Online (Sandbox Code Playgroud)
但是请注意,定义别名boost
可能与实际命名空间冲突boost
Run Code Online (Sandbox Code Playgroud)namespace alias_name = ...
...
alias_name
必须是以前未使用过的名称...
这样,一旦您实际包含一个 boost 标头,您就会遇到编译器错误:
// Existing namespace(s)
namespace boost {}
namespace another_name {}
// Conflicing alias_name.
namespace boost = another_name; // error: redefinition of 'boost
Run Code Online (Sandbox Code Playgroud)
如果您在代码库中看到过这个特定示例,则可能是为了尝试提供一个内部看似是 boost(子集)的 boost 实现,稍后可以通过删除别名并包含实际的 boost 标头来替换它,但无需更改使用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.
Run Code Online (Sandbox Code Playgroud)
后来internal_boost.h
被修改成
// internal_boost.h
#include "boost/mpl/identity.hpp"
Run Code Online (Sandbox Code Playgroud)
这种方法可以说可以更容易地促进变体(比如一个产品变体,其中 3rd 方库可能由于安全关键问题而无法使用),但它也可能使开发人员感到困惑,并且可以说更好的方法是提供一个简单设置的唯一别名为不同的变体/版本设置不同的值(而不是提供一个别名,该别名被命名为,然后被一个实际的知名命名空间完全替换,例如boost
)。