JiiPee <
n...@notvalid.com> wrote:
> Quick question. Sometimes I think whether to use enum class or enum.
Old-style enum, which was inherited from C, is essentially just almost purely
syntactic sugar for declaring compile-time int constants. While not exactly
the same thing (even in C), an enum like
enum Name { value1, value2, value3 };
is almost the same thing as saying
typedef int Name;
const int value1 = 0, value2 = 1, value3 = 2;
(Yes, it's not *exactly* the same thing, even in C, but in most practical
situations you can consider them the same thing.)
In most situations this is a bit problematic because all those names end up
in the surrounding scope (often the global namespace, if you declare that
enum in that scope). In order to minimize naming collisions you usually want
to manually prefix all those names, by naming them like
enum Name { Name_value1, Name_value2, Name_value3 };
or similar.
Strongly-typed enums (ie. "enum class") add modularity by not contaminating
the surrounding scope with all those names, and make the enumerated type an
actual user-defined type, rather than it being just an alias for an int.
Nevertheless, there are situations where old-style enums can be more
practical. After all, they are just effectively ints, and sometimes that's
useful. Namely, you can directly do arithmetic with them, while the same is
not possible (on purpose) with strongly-typed enums, without an explicit
cast to int (which makes it more awkward).
Most particularly, old-style enumerated values can be used as-is to index
an array, while strongly-typed enumerated values cannot (without an explicit
cast). Sometimes being able to index an array with enumerated names can be
handy (when those names refer to elements of an array).
Unfortunately there is no best-of-both-worlds alternative, ie. a "mixed"
style enumerated value which are inside the namespace scope of the enum
type but can be be used for integer arithmetic and array indexing as-is
without an explicit cast.
I suppose the closest you can get to that is by putting the old-style
enum inside a namespace (but then you can't use the name of that
namespace as the name of the enumerated type).