0

Possible Duplicate:
C++: Print out enum value as text

Say I have an enumeration:

typedef enum MyEnum_
{
  MY_ENUM_BLUE,
  MY_ENUM_RED,
  MY_ENUM_GREEN
} MyEnum;

And that I have a method that gets an "MyEnum" as parameter. I'd like write to log file the value of that MyEnum, but I don't want 0, 1 or 2 to appear there--- I'd like to output the actual enumeration string "MY_ENUM_xxxx", of course without a switch/case block..... and dealing with each value individually.

Is there some trickery or pattern, in c++ or using macros that would help me achieve that?

Community
  • 1
  • 1
JasonGenX
  • 4,952
  • 27
  • 106
  • 198
  • I believe these are compiler constants and not compiled into the code, unlike Java and C# which have metadata for types. – Mike Christensen Dec 12 '11 at 21:08
  • I know, that's why I also asked if there's a trick macro approach around this, that would alleviate the need for a lengthy switch/case block for each case... – JasonGenX Dec 12 '11 at 21:11

1 Answers1

1

No need to typedef in c++

enum MyEnum_
{
  MY_ENUM_BLUE,
  MY_ENUM_RED,
  MY_ENUM_GREEN
} MyEnum;

#define TOSTR(x) #x

const char *names[]={TOSTR(MY_ENUM_BLUE),
               TOSTR(MY_ENUM_RED),
               TOSTR(MY_ENUM_GREEN)};

int main(int argc, char *argv[])
{
   MyEnum_ e=MY_ENUM_RED;

   std::cout << names[e] << std::endl;

   return 0;
}
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77