匿名命名空间歧义

sha*_*p02 18 c++ namespaces anonymous ambiguity

请考虑以下代码段:

void Foo() // 1
{
}

namespace
{
  void Foo() // 2
  {
  }
}

int main()
{
  Foo(); // Ambiguous.
  ::Foo(); // Calls the Foo in the global namespace (Foo #1).

  // I'm trying to call the `Foo` that's defined in the anonymous namespace (Foo #2).
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如何引用匿名命名空间内的内容?

Geo*_*che 18

你不能.该标准包含以下部分(§7.3.1.1,C++ 03):

未命名的命名空间定义的行为就像被替换为

  namespace unique { /* empty body */ }
  using namespace unique;
  namespace unique { namespace-body }
Run Code Online (Sandbox Code Playgroud)

其中翻译单元中所有唯一的出现都被相同的标识符替换,并且该标识符与整个程序中的所有其他标识符不同.

因此,您无法引用该唯一名称.

但是,您可以在技术上使用以下内容:

int i;

namespace helper {
    namespace {
        int i;
        int j;
    }
}

using namespace helper;

void f() { 
    j++; // works
    i++; // still ambigous
    ::i++; // access to global namespace
    helper::i++; // access to unnamed namespace        
}
Run Code Online (Sandbox Code Playgroud)


Nik*_*sov 5

虽然Georg给出了标准的,正确的,正确的,可敬的答案,但我想提供我的hacky - 在匿名命名空间中使用另一个命名空间:

#include <iostream>

using namespace std;

namespace
{
namespace inner
{
    int cout = 42;
}
}

int main()
{
    cout << inner::cout << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)