# find enum elements

## Recommended Posts

Johngrey    128
In C++ what trick do you use to get number of elements in enum?

##### Share on other sites
Sneftel    1788
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.

##### Share on other sites
SirLuthor    364
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]

##### Share on other sites
Sneftel    1788
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]

##### Share on other sites
SirLuthor    364
Hehehe, do the words 'brutal and ungodly hack' mean anything to you? [grin]

##### Share on other sites
Sneftel    1788
Quote:
 Original post by SirLuthorHehehe, 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]

##### Share on other sites
Inmate2993    222
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.

##### Share on other sites
Dave Hunt    4872
Quote:
 Original post by Inmate2993Another 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.

##### Share on other sites
SirLuthor    364
... Because everyone knows that pens are the work of the devil, since 90% of everything you write will be rewritten. Repeatedly. [grin]