Get enum value by name

前端 未结 4 1354
甜味超标
甜味超标 2020-12-17 02:46

I have an enumeration, which contains hundreds of entries.

I will be getting the value of the enumeration as a string. Is there any way to convert the string into an

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 03:48

    Use the X-macro technique. Transcribing almost directly from Wikipedia:

    #define LIST_OF_COLORS \
        X(Red) \
        X(Green) \
        X(Blue) \
        X(Yellow)
    
    #define X(name) name,
    enum Colors { LIST_OF_COLORS };
    #undef X
    
    #define X(name) #name,
    char const * const ColorName[] = { LIST_OF_COLORS };
    #undef X
    

    Because enums automatically assign values counting from zero, and we can't accidentally repeat the list in a different order when we create the name array, using the enum as the index into the ColorName array will always point directly to the corresponding word, and you don't have to search when mapping in that direction. So:

    printf("%s\n", ColorName[Red]);
    

    Will print:

    Red
    

    And going the other way:

    enum Color strtoColor(char const *name)
    {
        for (int i = 0; i < sizeof(ColorName) / sizeof(*ColorName); i++)
            if (strcmp(ColorName[i], name) == 0)
                return (enum Color)i;
        return -1;
    }
    

    EDIT

    If you are using C++, then, Using X-macro on paddy's answer:

    static std::map colorMap;
    void InitColorMap()
    {
    #define X(name) colorMap[#name] = name;
        LIST_OF_COLORS
    #undef X
    }
    

    Or, stealing from this answer, in C++11:

    static std::map colorMap =
    {
    #define X(name) { #name, name },
        LIST_OF_COLORS
    #undef X
    };
    

    ... or whatever. That's not my language.

提交回复
热议问题