Namespaces are one honking great idea
The title of this post comes from the last line of The Zen of Python.
It applies to C++ too: namespaces are great. Namespaces let the Boost folks contain all sorts of widely varying libraries without having to worry about naming collisions in user code. Namespaces let you mix multiple libraries easily and safely. Namespaces let you group sets of related free functions together, without needing a class. Namespaces also let you work around one thing I've always found a bit unusual with enums: the way they don't have their own scope.
enum ValidValues { Value1, Value2 };
This ends up declaring Value1
and Value2
in the underlying scope. What I like to do is wrap the enum in a namespace:
namespace ValidValues { enum Enum { Value1, Value2 }; }
This sticks Value1
and Value2
in the ValidValues
namespace. The only disadvantage is declaring a variable of this enum type gets a bit silly and inconsistent. For example:
ValidValues var = Value1; // error, ValidValues is a namespace, Value1 is undefined ValidValues::Enum var = Value1; // error, Value1 is undefined ValidValues::Enum var = ValidValues::Value1; // okay
This is yet another area where C++0x will offer its own solution, in this case, strongly typed enumerations.