0

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?

Mossmyr
  • 909
  • 2
  • 10
  • 26
  • 1
    have you seen this ? https://stackoverflow.com/questions/18195312/what-happens-if-you-static-cast-invalid-value-to-enum-class – artm Nov 24 '19 at 21:45
  • 1
    What if `SomeEnum` is a bitmask? – ph3rin Nov 24 '19 at 21:53
  • `static_cast` might also appears to works if you cast a class to wrong derived class (if both class have same parent). One has to use `dynamic_cast` to do run-time validation. Maybe in C++ 23, it might become possible to do something if the language finally support querying the meta-data at compile time. Many would like for example to be able to get the string representation of an `enum` value which can be really helpful for human readable serialization. – Phil1970 Nov 25 '19 at 00:49
  • Thanks for that link @artm but the accepted answer is too advanced for me. I can't make heads nor tails from it. – Mossmyr Nov 25 '19 at 03:49

0 Answers0