
int to enum conversion. [?]
Quote:
> 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).
Quote:
> 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.
faa
--