Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate integer is some enum class item (C++11)

i have some enum class

enum class Foo { A=1, B=18 , Z=42 };

i want to check if some integer can be converted into a Foo. What would be the ideal way to do this? this is for runtime check (the integer is not known yet at compile-time)

Obviously i can do this the hard way (write a function bool CheckEnum(Foo); with a big-ass switch returning true for all cases except the default one), but i was hoping a more elegant mechanism that avoided so much writing. MPL or Boost.Preprocessor would be a perfectly acceptable solution, but one of which i sadly know very little about

like image 325
lurscher Avatar asked Nov 22 '11 03:11

lurscher


People also ask

How do you check if a value is a valid enum?

Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not.

Is enum a class in C?

Enum ClassC++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.

Are enums ints in C?

In C, each enumeration constant has type int and each enumeration type is compatible with some integer type. (The integer types include all three character types–plain, signed, and unsigned.) The choice of compatible type is implementation-defined.

Can enum values be numbers?

Numeric EnumNumeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


1 Answers

A solution to this problem is to ditch the enums, and replace it with some arrays which are created using XMACROs.

like image 160
EvilTeach Avatar answered Sep 29 '22 09:09

EvilTeach