I am reading an enum
value from a binary file and would like to check if the value is really part of the enum
values. How can I do it?
#include <iostream> enum Abc { A = 4, B = 8, C = 12 }; int main() { int v1 = 4; Abc v2 = static_cast< Abc >( v1 ); switch ( v2 ) { case A: std::cout<<"A"<<std::endl; break; case B: std::cout<<"B"<<std::endl; break; case C: std::cout<<"C"<<std::endl; break; default : std::cout<<"no match found"<<std::endl; } }
Do I have to use the switch
operator or is there a better way?
EDIT
I have enum values set and unfortunately I can not modify them. To make things worse, they are not continuous (their values goes 0, 75,76,80,85,90,95,100, etc.)
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
Then you can just do: values. contains("your string") which returns true or false.
An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .
enum
value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of enum X { A = 1, B = 3 }
, the value of 2
is considered a valid enum value.
Consider 7.2/6 of standard:
For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax. It is possible to define an enumeration that has values not defined by any of its enumerators.
There is no retrospection in C++. One approach to take is to list enum values in an array additionally and write a wrapper that would do conversion and possibly throw an exception on failure.
See Similar Question about how to cast int to enum for further details.
Maybe use enum like this:
enum MyEnum { A, B, C };
and to check
if (v2 >= A && v2 <= C)
If you don't specify values for enum constants, the values start at zero and increase by one with each move down the list. For example, given enum MyEnumType { ALPHA, BETA, GAMMA };
ALPHA has a value of 0, BETA has a value of 1, and GAMMA has a value of 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With