1

while there are solutions to easily convert an enum to a string, I would like the extra safety benefits of using enum class. Is there a simple way to convert an enum class to a string?

(The solution given doesn't work, as enum class can't index an array).

pseyfert
  • 2,865
  • 3
  • 21
  • 46
Mike H-R
  • 7,486
  • 5
  • 41
  • 63

2 Answers2

2

You cannot implicitly convert to the underlying type but you can do it explicitly.

enum class colours : int { red, green, blue };
const char *colour_names[] = { "red", "green", "blue" };
colours mycolour = colours::red;
cout << "the colour is" << colour_names[static_cast<int>(mycolour)];

It's up to you if that is too verbose.

sjdowling
  • 2,954
  • 2
  • 19
  • 30
1

Are you using VS C++. Below the code example of MSDN

using namespace System;
public ref class EnumSample
{
public:
   enum class Colors
   {
      Red = 1,
      Blue = 2
   };

   static void main()
   {
      Enum ^ myColors = Colors::Red;
      Console::WriteLine( "The value of this instance is '{0}'", myColors );
   }

};

int main()
{
   EnumSample::main();
}

/*
Output.
The value of this instance is 'Red'.
*/
LPs
  • 15,592
  • 8
  • 28
  • 58