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
  • 3,263
  • 3
  • 21
  • 47
Mike H-R
  • 7,726
  • 5
  • 43
  • 65
  • 3
    You could use a `std::unordered_map` instead. – Joseph Mansfield Jan 14 '15 at 09:28
  • _"The solution given doesn't work, as enum class can't index an array"_ Can you elaborate about this, or give a sample? I don't understand in which way it should be different for `enum class`. – πάντα ῥεῖ Jan 14 '15 at 09:29
  • 2
    @πάνταῥεῖ You cannot implicitly convert an `enum class` to its underlying type, which is kind of the point of them. – sjdowling Jan 14 '15 at 09:31
  • 1
    Array-based solutions aren't usable when the vaues in the enum are user-specified, like { Good= 1, Bad= 2, Unknown= ~0 } –  Jan 14 '15 at 09:39

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,994
  • 2
  • 21
  • 31
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
  • 16,045
  • 8
  • 30
  • 61
  • What about { Red= 0x100, Blue= 0x10000, Green= 0x1000000 } ? –  Jan 14 '15 at 09:36
  • 1
    Brilliant SSCE, could you explain the `^` syntax to me as I'm not familiar with it? – Mike H-R Jan 14 '15 at 09:43
  • @πάνταῥεῖ thanks, with c++cli I found an explanation of the syntax [here](http://stackoverflow.com/questions/202463/what-does-the-caret-mean-in-c-cli) – Mike H-R Jan 14 '15 at 09:52