I have the following enumerator and it's likely to be expanded over the course of program development:
enum myEnum {
Element1,
Element2,
Element3
...
ElementX
Last
};
I have a function that uses the enumerator in the following way:
bool CheckEnumValidity(myEnum a)
{
bool valid = false;
switch (a) {
case Element1:
case Element2:
case Element3:
case ...
case ElementX:
valid true;
break;
case Last:
valid false;
break;
};
return valid;
}
QUESTIONS:
1) I duplicate Element1
, Element2
etc. in two places in my program. How to get rid of the duplication in the safest way?
2) Should I have default
behavior that throws an exception (or return false
) in the aforementioned switch
statement given that CheckEnumValidity()
has an argument of myEnum
type?
NOTES:
C++ 11 is unavailable for my application.
Provided that your enum really doesn't contain any explicit value assignment then you can write: