Casting an int to an enum class works fine, despite the int in question not being a value in the enum:
#include <iostream>
enum class SomeEnum {
Foo = 1
};
int main(int argc, char** argv) {
SomeEnum e = static_cast<SomeEnum>(0); // cast works despite 0 not being a value in SomeEnum
std::cout << static_cast<int>(e) << std::endl;
}
$ ./a.out
0
This behaviour doesn't make a whole lot of sense to me, but ok. Is there any way to force the cast to fail (throw an exception, exit, return) when the value to be cast is not in the defined enum, without writing your own value_to_enum()
function?