How to Get enum item name from its value

后端 未结 10 956
天涯浪人
天涯浪人 2020-12-08 09:56

I declared a enum type as this,

enum WeekEnum
{
Mon = 0;
Tue = 1;
Wed = 2;
Thu = 3;
Fri = 4;
Sat = 5;
Sun = 6;
};

How can I get the item na

相关标签:
10条回答
  • 2020-12-08 10:27

    On GCC it may look like this:

    const char* WeekEnumNames [] = {
        [Mon] = "Mon",
        [Tue] = "Tue",
        [Wed] = "Wed",
        [Thu] = "Thu",
        [Fri] = "Fri",
        [Sat] = "Sat",
        [Sun] = "Sun",
    };
    
    0 讨论(0)
  • 2020-12-08 10:28

    You can't directly, enum in C++ are not like Java enums.

    The usual approach is to create a std::map<WeekEnum,std::string>.

    std::map<WeekEnum,std::string> m;
    m[Mon] = "Monday";
    //...
    m[Sun] = "Sunday";
    
    0 讨论(0)
  • 2020-12-08 10:29

    You can define an operator that performs the output.

    std::ostream& operator<<(std::ostream& lhs, WeekEnum e) {
        switch(e) {
        case Monday: lhs << "Monday"; break;
        .. etc
        }
        return lhs;
    }
    
    0 讨论(0)
  • 2020-12-08 10:31

    I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.

    It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).

    And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.

    0 讨论(0)
提交回复
热议问题