views:

329

answers:

2

I am using managed extensions in VS 2008

I want to print the name of an en enum value

This code used to be fine VS 2003

Enum::GetName(__typeof(COMMAND_CODES),__box(iTmp))

but now I get a comile error

here is my enum

typedef enum  { /* Command codes */
    UMPC_NULL = 0,
    } COMMAND_CODES

Any clues ? ;

+1  A: 

As far as I know, that is not possible in plain C++ since it doesn't have reflection.

You can use macros in plain C++ to workaround it:

#define COMMAND_CODES \ 
    ENUM_OR_STRING(CODE1), \ 
    ENUM_OR_STRING(CODE1),

// Enum
#define ENUM_OR_STRING(x) x
enum CommandCodes
{
    COMMAND_CODES
};
#undef ENUM_OR_STRING

// Names
#define ENUM_OR_STRING(x) #x    
char *CommandCodeNames[] =
{
    COMMAND_CODES
}; 
#undef ENUM_OR_STRING

Now the name of enum member is as easy to get as CommandCodeNames[(int)commandCode].

Filip Navara
Cheers but I had this code working in VS2003 .net 1.1 I guess
Kaya
Maybe the type can be passed in at compile time
Kaya
There's a big difference between *managed* and *unmanaged* code. The later one doesn't have reflection, so there's no such thing as Enum::GetName.
Filip Navara
There is if using managed extensions
Kaya
You asked for _unmanaged_ and that's what I am answering.
Filip Navara
If you were asking about the difference between C++/CLI and C++ w/ managed extensions in regard to the code you should have phrased your question that way.
Filip Navara
A: 

Can you use rtti typeid() and use the name() field?

Edit: From comment:

 Enum::GetName(COMMAND_CODES::typeid,iTmp)
Preet Sangha
I was thinking about that, but it doesn't work for enum members AFAIK.
Filip Navara
http://www.java2s.com/Tutorial/Cpp/0100__Development/Usingtypeidenumdatatype.htm ... agrees with me.
Filip Navara
Yes this works greatEnum::GetName(COMMAND_CODES::typeid,iTmp)
Kaya
Well there you. Awesome!
Preet Sangha
Nice one Preet, saved me!
Kaya