How to return an enum by item index as apposed to value index?

How do I index into an enum via "item index" instead of the "value indexing":

"Value indexing" (not useful to me with what I am doing):

eSerialBauds eBaud = static_cast<eSerialBauds>(1200); // yields eBaud1200

I want "item indexing": ( How to get the following? )

eSerialBauds eBaud = static_cast<eSerialBauds>(3); // to yield eBaud1200

// values (from WinBase.h)
#define CBR_110             110
#define CBR_300             300
#define CBR_600             600
#define CBR_1200            1200
#define CBR_2400            2400

enum class eSerialBauds
  eBaud110 = CBR_110,
  eBaud300 = CBR_300,
  eBaud600 = CBR_600,
  eBaud1200 = CBR_1200,
  eBaud2400 = CBR_2400,

Please note that I am given this enum class from another class. There are many. So I have to work with what is given to me.

I did write a work around method but it would be nice to have a more elegant way of getting the result.

2 answers

  • answered 2021-04-14 22:41 Paul Sanders

    Just set up an array containing the enum values, like this:

    static const eSerialBauds bauds_by_index [] = { eBaud110, eBaud300, eBaud600, eBaud1200, eBaud2400 };

    And then you can do, for example:

    eSerialBauds baud = bauds_by_index [3];

  • answered 2021-04-14 22:42 Jason

    The easiest way would be to build an array of the enum values.

    static const auto sBaudIndex = std::array<eSerialBaunds>{eBaud100, eBaud200, eBaud600, eBaud1200, eBaud2400);

    Then you index that array. It is fragile, but I know of no way to have the compiler enumerate the enum values for you.

    You could skip the enum if you don't need it, and just use the WinBase values in your array