命名空间中的未命名空间 [英] unnamed namespace within named namespace

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

问题描述

有人要求我修改某些代码,看起来像这样:

Some code I've been asked to modify looks rather like this:

namespace XXX {

namespace {

// some stuff

} // end of unnamed

// Some stuff within the scope of XXX

} // end of XXX

我正在努力查看将未命名的名称空间嵌入另一个名称空间的优势(如果有的话),并且我正在考虑将其更改为:

I'm struggling to see the advantage, if any, of embedding the unnamed namespace within another namespace and I'm considering changing it to:

namespace {

// some stuff

} // end of unnamed

namespace XXX {

// Some stuff within the scope of XXX

} // end of XXX

我们将不胜感激任何观点.

Any views would be gratefully appreciated.

推荐答案

好吧,结果发现 X::<anonymous>::foo()显示为X::foo() .我很惊讶.

Okay, turns out that X::<anonymous>::foo() is visible as X::foo(). I'm surprised.

因此,不,几乎没有实际好处.但是可能会涉及语义或文档含义.

So, no, there's very little practical benefit. There may be semantic or documentation implications though.

那取决于东西",不是吗?

Well that rather depends on the "stuff", doesn't it?

现有代码允许X中的代码具有私有"的其他内容,这些其他内容也位于X中,但不能从X外部进行访问:

The existing code allows code in X to have "private" other stuff that's also in X but cannot be accessed from outside of X:

#include <iostream>

namespace X {
   namespace {
      void foo() { std::cout << "lol\n"; }
   }

   void bar() { foo(); }
}

int main()
{
   X::bar();
   // X::foo();  // can't do this directly  [edit: turns out we can!]
}

  • 输出:lol\n
    • Output: lol\n
    • 您提出的方法使整个翻译部门都可以使用私有内容":

      Your proposed approach makes that "private stuff" available to the entire translation unit:

      #include <iostream>
      
      namespace {
         void foo() { std::cout << "lol\n"; }
      }
      
      namespace X {
         void bar() { foo(); }
      }
      
      int main()
      {
         X::bar();
         foo();     // works
      }
      

      • 输出:lol\nlol\n
        • Output: lol\nlol\n
        • 这篇关于命名空间中的未命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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