0

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.

11
  • nvm I read too fast. I retract my duplicate vote. This is not Conversion from int to enum class type possible? Commented Apr 14, 2021 at 22:35
  • Is my question clear enough for others? Commented Apr 14, 2021 at 22:37
  • 1
    I think so, I was just careless but left the comment so no one else votes it as a dup of that as well. Commented Apr 14, 2021 at 22:43
  • The target I used uses enum instead of enum class, but it's basically the same question. Just ping me if you think that's not an appropriate target. Commented Apr 14, 2021 at 22:55
  • The question was closed, but in case you want to keep the same syntax, you could do: replit.com/@Ranoiaetep/ExperiencedDeadTerabyte#main.cpp Commented Apr 14, 2021 at 23:15

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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

static constexpr auto sBaudIndex = std::array{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

1 Comment

std::array needs a template argument for the size, and you can make it constexpr.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.