find enum elements

Started by
7 comments, last by SirLuthor 18 years, 9 months ago
In C++ what trick do you use to get number of elements in enum?
Advertisement
This is a common idiom, although the exact naming varies:
enum FileType{    FILETYPE_FOO,    FILETYPE_BAR,    FILETYPE_BAZ,    NUM_FILETYPES};

In this case, of course, NUM_FILETYPES == 3.
Of course, Sneftel, that only works if you aren't assigning any values (that is, not counting straight up from 0) to the constants. Then your screwed [grin]
Free speech for the living, dead men tell no tales,Your laughing finger will never point again...Omerta!Sing for me now!
Not completely screwed. Here's an uncommon idiom that I just made up:

#define COUNTED_ENUM(type) enum { _ec ## type = __LINE__}; enum type#define ENUM_COUNT(type) NUM_ ## type ## s = (__LINE__ - _ec ## type - 2)COUNTED_ENUM(FileType){    FILETYPE_FOO = 3,    FILETYPE_BAR = 7,    FILETYPE_BAZ = 6,    ENUM_COUNT(FileType)};// NUM_FileTypes == 3


(warning: Don't actually use this, or clowns will eat you)

[Edited by - Sneftel on June 29, 2005 1:12:42 PM]
Hehehe, do the words 'brutal and ungodly hack' mean anything to you? [grin]
Free speech for the living, dead men tell no tales,Your laughing finger will never point again...Omerta!Sing for me now!
Quote:Original post by SirLuthor
Hehehe, do the words 'brutal and ungodly hack' mean anything to you? [grin]

Yes; they are music to my ears. I should submit this to Boost... they'd eat it up. [grin]
Its called basic addition, you raise one of your hands, and let each finger represent one of the items in the Enum. For each item, you raise a finger. When you're done, you count how many fingers are pointed up. My method suffers from a limited set of fingers. You could use your toes if you're that talented. Another alternative is to get toothpicks and place them on the table, one for each item in the enum. Another is to use a pencil, and write one tally for each item on the wall. To save space, and to make counting easier, put the fifth tally through the first four.
william bubel
Quote:Original post by Inmate2993
Another is to use a pencil, and write one tally for each item on the wall. To save space, and to make counting easier, put the fifth tally through the first four.


Alternatively, a pen can be used, but more care must be taken in the tally.
... Because everyone knows that pens are the work of the devil, since 90% of everything you write will be rewritten. Repeatedly. [grin]
Free speech for the living, dead men tell no tales,Your laughing finger will never point again...Omerta!Sing for me now!

This topic is closed to new replies.

Advertisement