开发者

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
}


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.


I use

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


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜