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

时间:2015-04-14 12:46:52

标签: c++ class namespaces

此代码无法编译:

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

用例类似于here

2 个答案:

答案 0 :(得分:4)

  

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

没有

你可以采取相反的方式:

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

答案 1 :(得分:1)

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

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

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

相关问题