int to enum conversion. [?] 
Author Message
 int to enum conversion. [?]

> According to the standard,
> "
> An expression of arithmetic or enumeration type can be converted to an
>   enumeration  type  explicitly.  The value is unchanged if it is in the
>   range of enumeration values of the  enumeration  type;  otherwise  the
>   resulting enumeration value is unspecified.

> "

> Now the questions are
> A. In the following code , how do I validate weather the conversion
> was
> `okay' - without exlcitly cycling through all the enum-values with ifs
> and else-ifs.(there could be lots of them).

According to the standard, no.  You can convert the enum values to an
integer type and compare each of them with the input value.  That's it.  Any
attempt to convert the integer without checking if it's one of the values in
the enum first is (as the standard says) "undefined".  But it's not that
bad.  Really.

If you can insure that the enum's representational values are within a
range, you can also do it with a simple bounds test against the minimum and
maximum representational value.  Even if your values are sparse, you can
usually come up with an efficient test tree to validate the value.  Even if
your values have been defined by the randomizer from hell, you can still use
a case statement (which is generally converted to good code by today's
compilers).  As a last resort, you can punt and just use an integer type (or
just let the enum hold bogus values and test before you use them - even
though the standard says "undefined", no compiler out there implements them
as anything other than another way of looking at an integral type and they
don't bomb on assigning "out of range" values).

> B. Is there any way to attach an 'algo' to the enum(say Number) to
> convert an int to an enumeration? That is I want the underlaying value
> to change(see quote form the standard above).

Not unless you wrap the enum in a class and add constructor methods that do
the checking.  Inline the methods and don't use virtual functions and you
generally add no overhead vs. the enum itself.  You can also add an
additional enumeration for bad or uninitialized values to add greater
safety, as well.  This is probably the best alternative.



Sun, 17 Feb 2002 03:00:00 GMT  
 [ 1 post ] 

 Relevant Pages 

1. conversion int to char, char to int ?????

2. Conversion of signed long int to n-bit signed int and vs vs

3. Getting back int value from Enum?

4. Getting enum int value from mnemonic

5. Getting enum int value from mnemonic

6. treating enum as int

7. enum, int and #define

8. is enum diffrent than int?

9. HELP - Can you TypeCast enum to short int?

10. Is int X found in enum Y?

11. int to enum when deserializing

12. How to create an enum from an int?


Powered by phpBB® Forum Software