0

Possible Duplicate:
Is there a simple script to convert C++ enum to string?

In the C# program below, while using enumeration Priority, i need the string "None" and not the id 0. The C# code for doing this is given below. Is there an elegant way of doing this in C++. Can a map be avoided in the C++ implementation.

enum Priority
{
    None,
    Trivial,
    Normal,
    Important,
    Critical
}

class Program
{
    static void Main()
    {
    // Write string representation for Important.
    Priority enum1 = Priority.Important;
    string value1 = enum1.ToString();

    // Loop through enumerations and write string representations. (See GetNames)
    for (Priority enum2 = Priority.None; enum2 <= Priority.Critical; enum2++)
    {
        string value2 = enum2.ToString();
        Console.WriteLine(value2); //outputs the string None, Trivial etc ...
    }
    }
}

public override string ToString()
{
    Type type = base.GetType();
    object obj2 = ((RtFieldInfo)GetValueField(type)).InternalGetValue(this, false);
    return InternalFormat(type, obj2);
}
Community
  • 1
  • 1
Martin
  • 3,396
  • 5
  • 41
  • 67

1 Answers1

5

In C++, an enum is nothing more than a bit of syntactic sugar around an integral literal. The compiler quickly strips the enumerator name away, so the runtime never has access to it. If you want to have a string name for an enum, you have to do it the hard way.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    +1, though it would be better to write *... syntactic sugar around an **integral literal*** instead of *... syntactic sugar around an **integer***. – Nawaz Oct 18 '11 at 05:27