I use
enum SomeEnum
{
FIRST = 1,
One = 1,
Two = 2,
Three = 3,
LAST = 3
}
I use
enum SomeEnum
{
FIRST = 1,
One = 1,
Two = 2,
Three = 3,
LAST = 3
}
it's not totally obvious what you are asking for, but supposing you have an enum like:
enum Fruits
{
Apples,
Bananas,
Pineapples,
Oranges,
};
You could modify it like so:
enum Fruits
{
Apples = 0,
Bananas,
Pineapples,
Oranges,
NUM_FRUITS; // must be last, and no other fruits can be given values.
};
The Apples = 0,
isn't strictly neccesary, it could still be just Apples,
because that will be the result by default, but it's a good idea because it makes it clear that you actually care what value it takes.
And thus, Fruits::NUM_FRUITS
would equal 4. If you added two more fruits, being careful to place them above the NUM_FRUITS
, and making sure the first fruit mentioned is set to zero, either implicitly or explicitly, then NUM_FRUITS
will instead be 6.
No, there's no general automatic solution after the enum's been created. If you're prepared to force people to declare their enums via a macro, and your compiler supports variadic macros, you can have a macro that creates the enum and captures the number of elements (stringify, scan for commas ignoring whatevers inside pairs of < >, ( ), [ ] etc..