C++ 语言特性02 - 命名空间
一:概述
现代C++中的命名空间是什么?
C++中的命名空间允许用户在命名空间范围内对类、方法、变量和函数等实体进行分组,而不是在全局范围内使用。这可以防止大型项目中的类、方法、函数和变量之间发生命名冲突。命名空间将开发人员编写的代码组织到不同逻辑范围中。因此,不同的用户可以在不同的进程中使用相同的方法和变量。
#include <iostream>namespace nsA
{void myf(){std::cout << "this is myf() function in nsA namespace\n";}
}int main()
{ nsA::myf(); // Let's use a method or function from nsA namespacesystem("pause");return 0;
}
在现代C++中,命名空间是一种库或框架。它们对于在不同的命名空间中保存相同命名的类、方法和其他实体非常有用。C++11标准和上面的其他标准,允许在命名空间定义中使用内联关键字,在这篇文章中,我们解释了如何在现代C++中使用内联命名空间。
C++11标准和上面的其他标准允许在命名空间定义中使用inline关键字。这样做是为了指定命名空间的成员可以被定义和专门化,就好像它们实际上属于封闭的命名空间一样。
在C++11和上述标准中,这种新构造称为内联命名空间,它解决了模板只能在其实际命名空间中进行专门化,而不能在其导入的命名空间中进行专门化的问题。
下面是内联命名空间的语法(从C++11开始)
inline namespace name_of_ns
{ // definition and declarations
}
从C++17开始,你可以使用任意数量的属性的可选序列,如下所示。
inline namespace <seq_attr> name_of_ns
{ // definition and declarations
}
二:例子1
namespace Lib
{inline namespace Lib_1{template <typename T> class A; }template <typename T> void g(T);
}struct MyClass { };
namespace Lib
{template<> class A<MyClass> { };
}int main()
{Lib::A<MyClass> a;g(a); // ok, Lib is an associated namespace of A
}
namespace Parent {namespace V1 {void foo() { std::cout << "foo v1.0" << std::endl; }}inline namespace V2 {void foo() { std::cout << "foo v2.0" << std::endl; }}
}int main()
{Parent::foo(); //V2::fooParent::V1::foo(); //V1:foo
}