...automatic way to do this. An enum is just a source code tag. The way to do it in C++ is the same as Euphoria:
enum
{
ONE = 1,
TWO = 2,
PURPLE = 3,
FIVE = 4,
GOLDFISH = 5,
NUM_VALUES = 5
};
const char *lookup[NUM_VALUES+1]={"","ONE", "TWO", "PURPLE", "FIVE", "GOLDFISH"};
Of course, if you leave off the numeric assignments in the enum, it auto-enums from 0, and NUM_VALUES ends up being the correct value, which is a nice property of the auto-enumeration-from-zero.
You can, of course, leave the NUM_VALUES out of the enum, and remove it from the array brackets, as long as you keep the lookup table the right size.
Keep in mind that arrays in C/C++ are indexed from zero, and hence the dummy entry at the beginning of the array.
There is another alternative: Using a preprocessor tuple.
#define MY_ENUMS \
MY_ENUM_TUPLE(ONE)\
MY_ENUM_TUPLE(TWO)\
MY_ENUM_TUPLE(PURPLE)\
MY_ENUM_TUPLE(FIVE)\
MY_ENUM_TUPLE(GOLDFISH)\
//end of the list
enum
{
#define MY_ENUM_TUPLE(x) x ,
MY_ENUMS
#undef MY_ENUM_TUPLE
NUM_VALUES
};
const char *lookup[NUM_VALUES]=
{
#define MY_ENUM_TUPLE(x) #x ,
MY_ENUMS
#undef MY_ENUM_TUPLE
};
which, if you're autonumbering from zero, automatically sets up both the enums and strings from a single initial mult-line preprocessor item.
Again, you can get rid of NUM_VALUES here if you have no use for it -- and in this case, this guarantees the string table is the right size, and everything's indexed from 0.
It is, of course, possible to do this _without_ the autonumbering, so if you absolutely need that, we can discuss workarounds.
|