在C++中,“命名空间别名”是什么?它如何使用?
命名空间别名是一种方便的方式,通过不同的短名称来引用长命名空间名称。
作为一个例子,假设你想要使用Boost的uBLAS中的数字向量而不使用using namespace
指令。每次都写完整的命名空间名称很麻烦:
boost::numeric::ublas::vector<double> v;
相反,你可以为boost::numeric::ublas
定义一个别名 -- 假设我们想将其缩写为ublas
:
namespace ublas = boost::numeric::ublas;
ublas::vector<double> v;
namespace Mine { class MyClass { public: int i; }; }
namespace His = Mine;
namespace Yours { class Mine: public His::MyClass { void f() { i = 1; } }; }
可以成功编译。帮助你解决命名空间/类名冲突的问题。
namespace Nope { class Oops { public: int j; }; }
#define Hmm Nope
namespace Drat { class Nope: public Hmm::Oops { void f () { j = 1; } }; }
还要注意,命名空间别名和using指令在编译时而非运行时解析。具体来说,它们都是用于告诉编译器在哪里查找名称的工具,如果在当前作用域或其任何父作用域中找不到特定符号,就可以使用这些工具。例如,以下两个示例都无法编译:
namespace A {
int foo;
namespace AA {
int bar;
} // namespace AA
namespace AB {
int bar;
} // namespace AB
} // namespace A
namespace B {
int foo;
namespace BA {
int bar;
} // namespace BA
namespace BB {
int bar;
} // namespace BB
} // namespace B
bool nsChooser1, nsChooser2;
// ...
// This doesn't work.
namespace C = (nsChooser1 ? A : B);
C::foo = 3;
// Neither does this.
// (Nor would it be advisable even if it does work, as compound if-else blocks without braces are easy to inadvertently break.)
if (nsChooser1)
if (nsChooser2)
using namespace A::AA;
else
using namespace A::AB;
else
if (nsChooser2)
using namespace B::BA;
else
using namespace B::BB;
constexpr
变量也在编译时使用,并想知道它们是否可以与别名或指令一起使用。据我所知,它们不能,尽管我可能对此有所错误。如果您需要在不同命名空间中使用相同名称的变量,并动态选择它们之间的区别,则必须使用引用或指针。// Using the above namespaces...
int& foo = (nsChooser1 ? A::foo : B::foo);
int* bar;
if (nsChooser1) {
if (nsChooser2) {
bar = &A::AA::bar;
} else {
bar = &A::AB::bar;
}
} else {
if (nsChooser2) {
bar = &B::BA::bar;
} else {
bar = &B::BB::bar;
}
}
更多相关内容请参见此链接
这篇文章主要介绍如何为一个很长的命名空间选择一个别名,例如:
namespace SHORT = NamespaceFirst::NameSpaceNested::Meow
然后,在以后的代码中,你可以使用typedef来简化操作:
typedef SHORT::mytype
而不是
typedef NamespaceFirst::NameSpaceNested::Meow::mytype
需要注意的是,这种语法只适用于命名空间,不能包含类或类型。
namespace foo {
class bar {
//define it
};
}
namespace baz {
class bar {
// define it
};
}
现在你有两个名为bar的类,由于命名空间而完全不同和独立。
你展示的 "using namespace" 是为了让你不必指定要使用命名空间中的类。例如,std::string 变成了 string。