在命名空间中的类中,我可以只退出**类命名空间吗

Within a class in a namespace, can I exit **just** the class namespace?

本文关键字:命名空间 退出 我可以      更新时间:2023-10-16

此代码不编译:

class A;
void foo(A&) {
}
class A {
void foo() {
foo(*this); ///This does not compile
}
};

错误:

error: no matching function for call to 'A::foo(A&)'
foo(*this);
^
note: candidate is:
note: void A::foo()

这可以通过调用::foo(*this);来解决


然而,让我们考虑一下我们在命名空间中的情况:

namespace bar {
class A;
void foo(A&) {
}
class A {
void foo() {
foo(*this); ///This does not compile
}
};
}

除了显式调用bar::foo(*this);之外,还有其他方法吗?我的意思是,有没有办法在下一个周围的声明性区域中查找名称,即包含的bar命名空间?

这个用例与这里看到的类似。

我的意思是,有没有办法在下一个周围的声明性区域中查找名称,即包含bar命名空间?

否。

你可以用另一种方式:

void foo() {
using bar::foo;
foo(*this); /// OK now
}

不在方法本身中。但是,您可以在.cpp文件中执行此操作:

namespace bar {
namespace {
auto outerFoo = foo;
}
void A::foo() {
outerFoo(*this);
}
}

请注意,名称outerFoo是一个隐藏的实现细节,它不会导致名称冲突(因为它位于匿名命名空间中)。