在命名空间的 class 中,我可以**仅**退出 class 命名空间吗?

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

此代码无法编译:

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 命名空间?

用例与看到的相似

I mean, is there any way to look up names in the next surrounding declarative region, i.e. the containing bar namespace?

没有

你可以反过来做:

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

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

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

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