0

I have this enum class in c++:

enum class type1 {
         A =10, B, C
};

and this switch statement:

switch (x) {
case 'A': case 'B': case 'C':
{
         v.push_back(int(type1(t[i])));
         break;
}
}

(v) is a vector of (ints) and (t) is a vector of (chars). I want to push the enum's (int) value into (v), but what I get is the (chars) value.

  • 1
    This enum class is not an `int`. There is no automatic conversion of any kind from chars or ints to enum class values. Just because one of the members of the enumerated class is named "A" doesn't mean that char "A" will be automatically converted to it, simply by casting. You have to do the job yourself: a lookup table, or a switch that individually converts each `char` or `int` to its corresponding value in the `enum class`. – Sam Varshavchik Feb 11 '18 at 20:41
  • Is this what you want? https://ideone.com/OZTzlC – Killzone Kid Feb 11 '18 at 20:57
  • I didn't want to write a separate block for each case. – user8386563 Feb 11 '18 at 21:41

1 Answers1

0

You are confusing variable names with character literals.

Once a C/C++ program is compiled, variable names are lost and cannot be introspected without lookup tables or other auxiliary mechanisms.

One workaround is to use C macros and stringify conversions instead of enum. Ugly but you can avoid lookup tables. Alternatively, create lookup tables that has variable name to char value mapping.

Look here for stringification using C preprocessor/macros: https://gcc.gnu.org/onlinedocs/gcc-3.4.4/cpp/Stringification.html

A typical lookup table can be as simple as a C array. Look here for an example: What's the best way to do a lookup table in C?

Adnan Y
  • 2,982
  • 1
  • 26
  • 29