使用其他命名空间内的命名空间函数

时间:2017-03-17 20:01:33

标签: c++

是否可以从顶级域名中的其他命名空间中省略某些函数的外部命名空间名称?

void sample_func();

namespace foo {
void first_func();

namespace bar {
void second_func();
void sample_func();
}

first_func()的所有内容都是微不足道的:只需输入using foo::first_func;就可以将其称为fist_func();

如果我想在没有任何前缀的情况下拨打second_func,一切都很简单:只有using foo::bar::second_func;允许将其称为second_func();

但有没有办法将其称为bar::second_func();?它会提高代码的可读性 - 更好地输入和查看类似bar::sample_func而不是完整foo::bar::sample_func的内容而不会出现名称混淆:显然using namespace foo::bar在这种情况下不是一个选项。

UPD 我对导入整个foobar命名空间(即using namespace ...指令不感兴趣!我只需要它们中的一些函数。

3 个答案:

答案 0 :(得分:1)

您可以使用

namespace bar = foo::bar;

foo::bar导入当前名称空间,只需bar

答案 1 :(得分:0)

如果不在名称空间中,则使用namespace::::作为前缀,即

::sample_func();

foo::first_func();
bar::second_func();
bar::sample_func();

答案 2 :(得分:0)

您可以使用

using namespace foo;

在您希望仅使用first_func()bar::sample_func()的任何声明性区域中。

示例:

int main()
{
   using namespace foo;
   first_func();
   bar::sample_func();
}
相关问题