Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I need anonymous namespace in a header?

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?

like image 739
Paolo.Bolzoni Avatar asked Sep 30 '14 10:09

Paolo.Bolzoni


People also ask

Should namespaces be in header files?

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.

What is the point of anonymous namespace?

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?

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.

Can you use namespace std in a header file?

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.


1 Answers

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.

like image 101
Paul Evans Avatar answered Sep 25 '22 17:09

Paul Evans