find enum elements

This topic is 4796 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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

Share on other sites
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
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
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
Hehehe, do the words 'brutal and ungodly hack' mean anything to you? [grin]

Share on other sites
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
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
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
... Because everyone knows that pens are the work of the devil, since 90% of everything you write will be rewritten. Repeatedly. [grin]

1. 1
2. 2
frob
16
3. 3
4. 4
5. 5
Rutin
10

• 18
• 13
• 14
• 76
• 22
• Forum Statistics

• Total Topics
632149
• Total Posts
3004363

×