【发布时间】:2017-04-14 23:57:23
【问题描述】:
阅读和研究了很多关于 C++11 新特性——“内联命名空间”的内容。我不明白这个特性的真正好处是什么。
我可以轻松地将“内联命名空间”中定义的所有函数/类型直接放置在封闭的命名空间中,并获得相同的结果。 那么将函数/类型放入内联命名空间的真正动机是什么? 对功能/类型进行分组? 使用“内联命名空间”是否有任何与 ADL 相关的好处? 我认为 ADL 的行为与此“内联命名空间”的隐式“使用”指令相同。
编辑1:
所以我认为以下是关键优势。 假设最初我们有这个:
namespace toplevel {
// Users can use toplevel::MyType
inline namespace current {
class MyType {};
} // inline namespace current
} // ns toplevel
现在,有一些新要求,我们需要一个新版本 可用,但保持旧的完整:
namespace toplevel {
// Users can use toplevel::MyType
// we can let the users know that we are going to deprecate it
// in favor of toplvel::next::MyType
inline namespace current {
class MyType {};
} // inline namespace current
// Users can use toplevel::next::MyType
namespace next {
class MyType {};
} // namespace next
} // ns toplevel
最后做到这一点。内联移动到“下一个”命名空间 它是默认值。仍然让用户访问“当前”但是 显式 ::current - 即这样:toplevel::current::MyType 顺便说一句 - 我的偏好甚至会将“当前”重命名为“已弃用”。
namespace toplevel {
// Users can still use it by referring
// to toplevel::current::MyType
namespace current {
class MyType {};
} // inline namespace current
// Have this one the default one
// under toplevel
// Users can use the new one this way: toplevel::MyType
inline namespace next {
class MyType {};
} // namespace next
} // ns toplevel
这听起来像是一个正确的场景吗?
【问题讨论】:
-
名称修改和版本链接是一些主要动机。
-
好的。所以版本控制确实是主要动机之一。再次阅读what-are-inline-namespaces-for,我认为这个想法是能够提供像 std::vector 这样的默认值,但如果新编译器的 std libc++ 的向量不是,则允许用户能够回退到 std::pre_cxx_1997::vector运作良好。所以我想这个不错的功能是使用 lnline 的关键优势。我将编辑我的问题。
标签: c++ c++11 namespaces