2

Possible Duplicate:
(How) can I count the items in an enum?

Is there a way to get the number of constants in enum?
For example:

enum C{id,value};

And later this would return 2:

//pseudo code
get<C>::value 

And also, is it possible to access those constants via [] optor? Like i.e.:
C[0] would return id

Community
  • 1
  • 1
smallB
  • 16,662
  • 33
  • 107
  • 151

2 Answers2

5

Usually, you start at zero and the last member gives the size of the enum excluding it.

enum C { id = 0, value, size };

C::size is the size of the enum. Is it possible to access those constants via subscript? No, it is unfortunately most assuredly not possible. However, in this case, you don't really want an enum- you just want a constant array.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • The word ***usually*** being the key :) – Armen Tsirunyan Jul 23 '11 at 19:33
  • 4
    Actually, it's just `size`, not `C::size` here. enums inject their constant values into the containing scope. As such, usually you want to use `C_size` or something as the name instead – bdonlan Jul 23 '11 at 19:34
1

A common idiom used for this is

enum C {
    id,
    value,
    LAST_ENUM_C // or something similar.
};

but that assumes no gaps in the enum values here (i.e. no id = 3, value = 15).

hlovdal
  • 26,565
  • 10
  • 94
  • 165