[c++] Enum to String C++

I commonly find I need to convert an enum to a string in c++

I always end up doing:

enum Enum{ Banana, Orange, Apple } ;

char * getTextForEnum( int enumVal )
{
  switch( enumVal )
  {
  case Enum::Banana:
    return "bananas & monkeys";
  case Enum::Orange:
    return "Round and orange";
  case Enum::Apple:
    return "APPLE" ;

  default:
    return "Not recognized..";
  }
}

Is there a better or recognized idiom for doing this?

This question is related to c++ enums

The answer is


You could throw the enum value and string into an STL map. Then you could use it like so.

   return myStringMap[Enum::Apple];

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];