In C++03, enumerations are declared as follows:
As can be seen, Hearts
is in the global namespace. This could give rise to potential name collisions with other enums.
Another issue is that it is difficult to find instances of a particular enum via ‘Find in Files’. If you are coding in Visual Studio, IntelliSense can’t assist by showing possible completions as it doesn’t know the context.
There are various workarounds. The best one I’ve found is to use a consistent prefix, as shown below:
This is just a convention and is difficult to enforce. It doesn’t really solve the problem but makes searching easier.
In C++11, we can use scoped enums:
enum class Suit
{
Hearts, Diamonds, Clubs, Spades
};
Suit suit = Suit::Hearts;
if (suit == Suit::Clubs) ...
Some nice features of this approach are:
- Avoids polluting global namespace.
- Works really well with Intellisense.
- Consistent with C# / Java.