Polymorphic Enums?
In C++, we often use polymorphism to allow old code to handle new
code–for instance, as long as we subclass the interface expected by a
function, we can pass in the new class and expect it to work correctly
with the code that was written before the new class ever existed.
Unfortunately, with enums, you can’t really do this, even though there
are occasional times you’d like to. (For instance, if you were
managing the settings for your program and you stored all of them as
enum values, then it might be nice to have an enum, settings_t, from
which all of your other enums inherited so that you could store every
new enum in the settings list. Note that since the list contains
values of different types, you can’t use templates.)If you need this kind of behavior, you’re forced to store the enums as
integers and then retrieve them using typecasts to assign the
particular value to the setting of interest. And you won’t even get
the benefit of dynamic_cast to help you ensure that the cast is
safe–you’ll have to rely on the fact that incorrect values cannot be
stored in the list.
I’m quoting from a C++ programming tutorial.
Can anybody please explain more deeply and with some examples how Polymorphic Enums work?
And in the case I have templates?
Simply stated, an
enumis simply a named constant value, for instance:In the above example,
setting_number_Xis simply a named constant for the valueX, as enumeration values start at 0 and increase monotonically.Keeping these then, in some type of container gives a basic storage type of integers, but can still be somewhat typesafe.
Now, suppose you wanted to add additional specific setting types and keep them all in a container.
Now, if you wanted to keep all the settings in a single container, you cannot safely. You could store all the integral values in a container of
std::vector<int>or similar, but that breaks down in that you cannot determine what integral types belong to what setting enumerations. Also, since the types are different you cannot store them in a single type-safe container.The correct way to go about this is would be to store the functionality of the setting in the container, something like this: