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

Using functions from namespace inside other namespace

本文关键字:命名空间 函数 其他      更新时间:2023-10-16

有什么方法可以省略顶级命名空间中其他命名空间中某些函数的外部命名空间名称吗?

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 ...指令!我只需要他们的一些功能。

您可以使用

namespace bar = foo::bar;

foo::bar作为 bar 导入到当前命名空间中。

如果不

在命名空间中,则用namespace::::作为前缀,即

::sample_func();
foo::first_func();
bar::second_func();
bar::sample_func();
您可以使用

using namespace foo;

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

例:

int main()
{
   using namespace foo;
   first_func();
   bar::sample_func();
}