Why an unnamed namespace is a "superior" alternative to static? [duplicate]

Solution 1:

  • As you've mentioned, namespace works for anything, not just for functions and objects.
  • As Greg has pointed out, static means too many things already.
  • Namespaces provide a uniform and consistent way of controlling visibility at the global scope. You don't have to use different tools for the same thing.
  • When using an anonymous namespace, the function/object name will get mangled properly, which allows you to see something like "(anonymous namespace)::xyz" in the symbol table after de-mangling, and not just "xyz" with static linkage.
  • As pointed out in the comments below, it isn't allowed to use static things as template arguments, while with anonymous namespaces it's fine.
  • More? Probably, but I can't think of anything else right now.

Solution 2:

One reason may be that static already has too many meanings (I can count at least three). Since an anonymous namespace can encapsulate anything including types, it seems superior to the static solution.

Solution 3:

There are two reasons I think:

  • static has two different meanings: at class scope, it means shared by the whole class while at file/function scope it affects the visibility/storage...
  • unnamed namespaces allow to declare new struct, class and typedef

One note though, the commitee backpedaled on this: static is no longer marked as deprecated in n3225.