匿名命名空间歧义 [英] Anonymous Namespace Ambiguity

查看:171
本文介绍了匿名命名空间歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

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).
}



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

How can I refer to something inside an anonymous namespace in this case?

推荐答案

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

You can't. The standard contains the following section (§7.3.1.1, C++03):


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

An unnamed-namespace-definition behaves as if it were replaced by



  namespace unique { /* empty body */ }
  using namespace unique;
  namespace unique { namespace-body }





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

where all occurrences of unique in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.

$

因此你无法引用这个唯一的名称。但是你可以在技术上使用类似下面的代码:

You could however technically use something like the following instead:

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        
}

这篇关于匿名命名空间歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆