unnamed namespace within named namespace

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.


Original answer

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

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!]
}
  • 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
}
  • Output: lol\nlol\n

It does have practical benefit. An unnamed namespace hide names inside it from different translation units.

The above code works only because the definition of foo is in the same translation unit.

Suppose main() and the definition of foo() are in different translation unit. It would compile, since the main file include the header of the declaration. but it wouldn't link because logically there's no such thing as X::(unnamed namespace)::foo.

Tags:

C++

Namespaces