Reputation: 3695
Let's say you have an enum class with several values. Using the enum class makes the code more typesafe, but the issue I run into is that I often have switch statements on the enum, which are supposed to handle all cases. What I'll typically do, is have the default throw an exception, the issue being that I'd rather have a compile time errror.
One possibility is to replace the enum with a class which has locally defined structs, and then instead of a switch statement, I could template the function call, such that I would have to define the function which handles each struct type. This only works for cases where the "enum" is compile time, not runtime.
Another option, is to make each "enum" a class which derives from an abstract base, which defines all of the required functions. The problem with that is that it doesn't separate the data, which is of certain types, from the handler of the data. i.e. the data type has to know about all handlers of the data.
What kinds of patterns do you use for these cases which allow the data, and the processor of the data to be able to be coded independently.
Ideally there would be a way to mark a switch statement for enums, such that all enums need to be handled in the switch statement. i.e. if you do not define a default, the compiler checks to see if every enum is covered at compile time.
Thoughts?
Upvotes: 2
Views: 1819
Reputation: 2647
A compile time check is definitely what you want. The big-3 compilers have command line options to achieve that.
-Wswitch
warning that checks for exactly that. You turn it into an error with -Werror=switch
./We4062
.Now you can forget to cover an enumerator in your switch and get a compilation error. Important detail: The switch must not contain a default
case.
Upvotes: 7