c++namespacescoding-style

Should every class have its own namespace?


Something that has been troubling me for a while:

The current wisdom is that types should be kept in a namespace that only contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions.

Does this imply that all classes must have a namespace of their own? If we assume that a class may be augmented in the future by the addition of non-member functions, then it can never be safe to put two types in the same namespace as either one of them may introduce non-member functions that could interfere with the other.

The reason I ask is that namespaces are becoming cumbersome for me. I'm writing a header-only library and I find myself using classes names such as project::component::class_name::class_name. Their implementations call helper functions but as these can't be in the same namespace they also have to be fully qualified!

Edit:

Several answers have suggested that C++ namespaces are simply a mechanism for avoiding name clashes. This is not so. In C++ functions that take a parameter are resolved using Argument Dependent Lookup. This means that when the compiler tries to find a function definition that matches the function name it will look at every function in the same namespace(s) as the type(s) of its parameter(s) when finding candidates.

This can have unintended, unpleasant consequences as detailed in A Modest Proposal: Fixing ADL. Sutter and Alexandrescu's rule states never put a function in the same namespace as a class unless it is meant to be part of the interface of that class. I don't see how I can obey that rule unless I'm prepared to give every class its own namespace.

More suggestions very welcome!


Solution

  • To avoid ADL, you need only two namespaces: one with all your classes, and the other with all your loose functions. ADL is definitely not a good reason for every class to have its own namespace.

    Now, if you want some functions to be found via ADL, you might want to make a namespace for that purpose. But it's still quite unlikely that you'd actually need a separate namespace per class to avoid ADL collisions.