I want to initialize a strongly-typed enum in C++11 from its underlying type, which is a value I read from serialized stream and which I have to check for a correct number range.
Something like:
enum class MyEnum {
FOO, BAR
};
MyEnum test = static_cast<MyEnum>(1);
This works as expected, but the problem is:
MyEnum test2 = static_cast<MyEnum>(42);
also works and give no indication of an Error. As far as I see an enum class also does not have any notion of bounds or other indicators on how to check if the input is valid. In "old style" enums, we would include a MIN and MAX value and compare against those, but adding these values to the strongly-typed enum would add invalid values to this type again, undermining its purpose.
Any ideas how I could check the bounds or force an error in case the value is out of bounds?
Update:
I just tried std::numeric_limits, but this also does not work for enum classes:
cout << static_cast<unsigned int>(numeric_limits<MyEnum>::min()) << endl;
cout << static_cast<unsigned int>(numeric_limits<MyEnum>::max()) << endl;
both return 0.