Andrew
Andrew

Reputation: 295

C++ boost how to get a number of members in enum?

is there anything in the boost which could help to get a number of members in enumeration?

e.g. to return 3 for the following code:


enum SomeEnum
{
  One,
  Two,
  Three
}

Upvotes: 0

Views: 861

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106126

No, there's no general automatic solution after the enum's been created. If you're prepared to force people to declare their enums via a macro, and your compiler supports variadic macros, you can have a macro that creates the enum and captures the number of elements (stringify, scan for commas ignoring whatevers inside pairs of < >, ( ), [ ] etc..

Upvotes: 0

SingleNegationElimination
SingleNegationElimination

Reputation: 156188

it's not totally obvious what you are asking for, but supposing you have an enum like:

enum Fruits
{
   Apples,
   Bananas,
   Pineapples,
   Oranges,
};

You could modify it like so:

enum Fruits
{
   Apples = 0,
   Bananas,
   Pineapples,
   Oranges,
   NUM_FRUITS; // must be last, and no other fruits can be given values. 
};

The Apples = 0, isn't strictly neccesary, it could still be just Apples, because that will be the result by default, but it's a good idea because it makes it clear that you actually care what value it takes.

And thus, Fruits::NUM_FRUITS would equal 4. If you added two more fruits, being careful to place them above the NUM_FRUITS, and making sure the first fruit mentioned is set to zero, either implicitly or explicitly, then NUM_FRUITS will instead be 6.

Upvotes: 6

Jason Iverson
Jason Iverson

Reputation: 2630

I use

enum SomeEnum
{
  FIRST = 1,
  One   = 1,
  Two   = 2,
  Three = 3,
  LAST  = 3
}

Upvotes: 2

Related Questions