In C++ an anonymous namespace is equivalent to:
namespace $$$$ {
//something
}
using namespace $$$$;
Where $$$$ is some kind of unique identifier. Anonymous namespace 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 anonymous 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?
Code in header files should always use the fully qualified namespace name. The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members.
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
Do not define an unnamed namespace in a header file. When an unnamed namespace is defined in a header file, it can lead to surprising results. Due to default internal linkage, each translation unit will define its own unique instance of members of the unnamed namespace that are ODR-used within that translation unit.
Since you can't put a namespace using statement at the top level of the header file, you must use a fully qualified name for Standard Library classes or objects in the header file. Thus, expect to see and write lots of std::string, std::cout, std::ostream, etc. in header files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With