3

I have C++ code that uses a bitset to store which values of an enum were found in my data structures (it's actually a bit more complex, but that doesn't matter for the question).

This means that when I have an enum like this:

enum Color
   {
     RED
   , GREEN
   , BLUE
   };

I want to define my bitset like this:

std::bitset<3>

Of course I don't want to hard-code the value 3.

In some cases I can simply add a 'terminator' to the enum, like this:

enum Color
   {
     RED
   , GREEN
   , BLUE
   , _COLOR_TERMINATOR
   };

And I can write this:

std::bitset<_COLOR_TERMINATOR>

But I cannot do this in all of my enums. If I would do this on some of my enums, code-checkers (like Lint) would complain that not all enum-values are used in a switch-statement.

Is there a way to get the maximum of the values in an enum without changing something in the enum itself? E.g. something like std::max<Color>?

Using Visual Studio 2013 and C++.

Thanks.

Patrick
  • 23,217
  • 12
  • 67
  • 130

2 Answers2

2

Maybe you could use a trait specialized for your enums to add the max defined value

template<class T> struct top_bound;
template<> struct top_bound<Color>{ static const size_t value = 3;};

and then

std::bitset<top_bound<Color>::value> my_bitset;

You still have to change the trait each time the enum changes, but you have only one explicit place to do it.

Qassim
  • 96
  • 3
0

If you write the following, does your version of lint complain?

enum Color
 {
   RED
 , GREEN
 , BLUE
 , LAST_COLOR = BLUE
 };

This definition of LAST_COLOR is relatively easy to maintain (you only have to change it when you add or remove a color at the end, not when you insert or remove colors at other places, and when inserting or deleting a color forces you to change two lines they at least are consecutive lines of your code). You then can write, for example,

std::bitset<LAST_COLOR + 1>

Alternatively, immediately after defining enum Color, how about

static const size_t _COLOR_TERMINATOR = BLUE + 1;
David K
  • 3,147
  • 2
  • 13
  • 19