kuga
kuga

Reputation: 1765

How to iterate over all elements of an enum in C++98

Referencing this question, I ask, what is the best way (as in general, least error prone approach) to iterate over all enum values in C++98?

Limitations of C++98:

What should be avoided in the solution (I am pretty sure, not everything can be avoided):

Upvotes: 1

Views: 196

Answers (2)

eerorika
eerorika

Reputation: 238401

There is no way to achieve all of your A..E. You can achieve:

  • BCDE by using macroes (e.g. #define CREATE_ENUM(...)).
  • ABDE by storing all elements in an array
  • ABC by only using consequtive starting from 0 and adding extra element to represent the count (as shown here) or more generally, values that can be represented as a mathematical sequence.

Note that neither enum classes nor range-for loops bring anything that would widen your choices as far as these points are concerned in the current C++ standard.

Upvotes: 1

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14613

Usual trick of that time was to do this:

enum Foo {
  One,
  Two,
  Three,
  Last,
  MAX_FOO_ENUM
};

for( int it = One; it < MAX_FOO_ENUM; ++it )
...

Of course it works correctly correct only if there is no skips in Foo. There is no way you can do that correctly otherwise unless you define some kind of container with elements in it equal to each value of Foo, but it's true for later standards too.

Upvotes: 0

Related Questions