Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if enum value is valid?

Tags:

c++

enums

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.)

like image 633
BЈовић Avatar asked Feb 11 '11 12:02

BЈовић


People also ask

Can you use == for enums?

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.

How do you check if a String exists in enum?

Then you can just do: values. contains("your string") which returns true or false.

Is enum value or reference?

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 .


2 Answers

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.

like image 176
Leonid Avatar answered Sep 17 '22 23:09

Leonid


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.

like image 37
Andrew Avatar answered Sep 16 '22 23:09

Andrew