在我的代码中有好几次我写了类似的东西
// all these using
using this::is::a::very::long::name::space::var1;
using this::is::a::very::long::name::space::var2;
using this::is::a::very::long::name::space::var3;
using this::is::a::very::long::name::space::fun1;
using this::is::a::very::long::name::space::fun2;
// to make this line cleaner
fun1(var1,fun2(var2,var3));
因为除了我列出的5个名称之外,我不想让该名称空间中的任何名称可用。
C++是否提供了使用所有这些名称的功能,而不必一遍又一遍地编写作用域的公共部分?
您的问题中的一个关键点似乎是您需要经常这样做。为了缓解这种情况,您可以在指定的名称空间中对这些符号进行素数化。
namespace common_stuff {
// You can also use an alias as the other answer suggests to shorten this
using this::is::a::very::long::name::space::var1;
using this::is::a::very::long::name::space::var2;
using this::is::a::very::long::name::space::var3;
using this::is::a::very::long::name::space::fun1;
using this::is::a::very::long::name::space::fun2;
}
using声明就是一个声明,因此我们创建了一个命名空间,其中只包含五个声明,以满足您的需求。现在,在每一个范围中,您都希望这五个范围对于非限定名称查找可见,您可以简单地添加
using namespace common_stuff;
并且只有common_stuff
中的这五个符号将可见。
您可以使用namespace
别名:
// Create an alias namespace of the long namespace
namespace shorter = this::is::a::very::long::name::space;
using shorter::var1;
using shorter::var2;
using shorter::var3;
using shorter::fun1;
using shorter::fun2;
如果使别名足够短,则可能根本不需要using
声明。但除此之外,没有任何其他方便的方法可以在不插入所有内容的情况下从命名空间中插入少量符号。
C++缺乏任何方法使符号x
、y
、z
从某个命名空间ns
可见,而不需要重复的using
声明。