简体   繁体   English

当外部名称空间的成员具有相同的名称时,访问未命名名称空间的成员

[英]Accessing member of an unnamed namespace when the outer namespace has a member with the same name

Here is the test code 这是测试代码

extern "C" {int printf(const char *, ...);}
namespace PS
{
   int x = 10; // A
   // some more code

   namespace {    
      int x = 20; // B
   }
   // more code
}

int main()
{
   printf("%d", PS::x); // prints 10
}

Is there any way to access inner(unnamed) namespace's x inside main ? 有什么办法可以访问main内部的内部(未命名)名称空间的x

I dont want to change code inside PS . 我不想更改PS代码。 Apologies if the code looks highly impractical. 如果代码看起来不切实际,则表示歉意。

PS: I tend to use the name x quite often. PS:我倾向于经常使用名字x

No. The only way to specify a namespace is by name, and the inner namespace has no name. 否。指定名称空间的唯一方法是按名称,内部名称空间没有名称。

Assuming you can't rename either variable, you could reopen the inner namespace and add a differently-named accessor function or reference: 假设您不能重命名任何一个变量,则可以重新打开内部名称空间并添加一个不同名称的访问器函数或引用:

namespace PS {
    namespace {
        int & inner_x = x;
    }
}

printf("%d", PS::inner_x);

One way is to add this code: 一种方法是添加以下代码:

namespace PS
{
   namespace
   {
      namespace access
      {
          int &xref = x;
      }
   }
}

and then you can access what you want: 然后您可以访问所需内容:

std::cout << PS::access::xref << std::endl; //prints 20!

Demo : http://ideone.com/peqEs 演示: http : //ideone.com/peqEs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM