Re: Efficient Enum Access...
Thomas Lehmann ha scritto:
We can not save enums except as an integer
value and so it's possible that a value might
not be suitable when converting back to
the enum type.
How can I check wether a given value is
contained by a given enum?
- when possible I would like to keep the original enum!
- I would like keeping the capability of reading
the enum values while debugging!
- of course, a generic approach is favorable.
The problem is interesting, however, it has, to my knowledge, no valid
solution in the language. First of all, let's get rid of a little
misconception about enumerations. For example, consider this definition:
enum E
{
a = 10, b = 100
};
you may think that the only valid values of E are a and b, and that
E x = E(50);
would be bad or unsafe or ill-formed. Well, it may be bad or unsafe, but
it's perfectly legal! It's right there, in 7.2/6: "It is possible to
define an enumeration that has values not defined by any of its
enumerators." In fact, all numbers from 0 to 127 (included) are allowed,
where 127 is the least integer of the form 2^M-1 greater than or equal
to 100. (the computation of the range extremes is a bit obscure in
C++03, but was made more clear in the draft for C++0x)
If this comes as a surprise to you, consider that valid uses of
enumerations are bit-masks types, for example:
enum BitMask { Bit0 = 1, Bit1 = 2, Bit2 = 4 };
inline BitMask operator|(BitMask m1, BitMask m2)
{
return BitMask(int(m1) | int(m2));
}
BitMask m = Bit0 | Bit2; // m == 5
This also explains why all values up to 2^M-1 are considered valid.
Now, to the main point, your problem is a kind of introspection: it's
equivalent to have the possibility to know the list of enumerators at
runtime. Unfortunately, the language doesn't help you. If you want to do
so, you need some extra-language tool able to statically inspect the
source code and generate some table that you could then compile in your
program and access at runtime. Not a difficult task, but annoying, I know.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]