Like most strongly typed languages, C++ has a way to group a set of constants together as their own type called enums. Enums are extremely useful in a wide variety of circumstances. However, enums in C++ have a lot of problems, and, in fact, they’re really a mess. I’m certainly not the only person to complain about this, either.
Enums don’t fit in with the rest of the language. They feel like something that was tacked onto the language to me. This is purely an aesthetic issue, and the fact that they’re useful in a wide variety of circumstances probably negates this.
More practically, you can’t control the conversion of the enum to and from integers. For example, you can use the less than operator to compare an enum and an integer without using a cast. This can result in accidental conversions that don’t make sense.
Perhaps the worst problem is the scope of the constants defined by the enum. They are enclosed in the same scope as the enum itself. I’ve seen a lot of code where people prepend an abbreviation of the enum’s type to each of the enum’s constants to avoid this problem. Adding the type to the name of a constant is always a good sign that something bad is happening.
In addition, you can’t decide ahead of time what the size of your enum’s type is. C++ normally tries to give the programmer as much control as possible. In the case of enums, this allows the compiler to store your enum in whatever type it wants to. Frequently, this doesn’t matter, but when it does matter, you’ll end up copying the value into an integer type that’s less expressive than than the enum.
After the break, I’ll explain what other languages are doing about it, what the next iteration of the C++ standard will do about it, and what you can do about it now. Continue reading