Search code examples
c++namespacesheader-filesunnamed-namespace

What if I need an unnamed namespace in a header?


In C++ an unnamed namespace is equivalent to:

namespace $$$$ {
  //something
}
using namespace $$$$;

Where $$$$ is some kind of unique identifier. Unnamed namespaces are then useful for code that should not be seen outside the compilation unit.

So far so good, however recently I started to write some code with templates, such code must be in headers so using unnamed namespaces does not make much sense as the mere inclusion of the header will nullify the isolation effect.

Then the question is, what is the suggested way in this cases? I started using a named namespace called Private. It does not really stop anyone who wants to use the identifiers inside, but at least it reduces the name clashes to id "Private."

Are there better ways? Suggestions?


Solution

  • Stick with your Private namespace (or use the more popular detail). Remember the main idea behind C++ access mechanisms is make it difficult to misuse them, not impossible. Protect yourself against accidents, not malicious attacks.