fuenfundachtzig fuenfundachtzig - 1 year ago 80
C++ Question

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

This question came to my mind, when I had something like

enum Folders {FA, FB, FC};

and wanted to create an array of containers for each folder:

m_containers[FA] = ...; // etc.

(Using maps it's much more elegant to use:
std::map<Folders, ContainerClass*> m_containers;

But to come back to my original question: What if I do not want to hard-code the array size, is there a way to figure out how many items are in Folders? (Without relying on e.g.
being the last item in the list which would allow something like
if I'm not mistaken.)

Answer Source

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

So then you can do:


Still not very nice though.

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

edit: as requested, made the special entry stick out more.