String to enum in C++

后端 未结 10 1626
渐次进展
渐次进展 2020-11-28 07:15

Is there a way to associate a string from a text file with an enum value?

The problem is: I have a few enum values stored as string in a text file which I read on

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 07:59

    Is this what you want? The initialization is straight, and no instantiation is needed.

    usage:

    enum SomeEnum
    {
        ENUM_ONE,
        ENUM_TWO,
        ENUM_THREE,
        ENUM_NULL
    };
    
    DEFINE_PAIRLIST(CEnumMap, SomeEnum)
    
    INIT_PAIRLIST(CEnumMap)=
    {
            {"One", ENUM_ONE},
            {"Two", ENUM_TWO},
            {"Three", ENUM_THREE},
            {"", ENUM_NULL}
    };
    
    main{
        // Get enum from string
        SomeEnum i = CEnumMap::findValue("One");
    
        // Get string from enum
        SomeEnum eee = ENUM_ONE;
        const char* pstr = CEnumMap::findKey(eee);
        ...
    }
    

    library:

    template 
    struct CStringPair
    {
        const char* _name;
        T _value;
    };
    
    template 
    struct CStringPairHandle
    {
        typedef CStringPair CPair;
        static const CStringPair * getPairList(){
            return Derived::implementation();
        }
        static T findValue(const char* name){
            const CStringPair * p = getPairList();
            for (; p->_name[0]!=0; p++)
                if (strcmp(name,p->_name)==0)
                    break;
            return p->_value;
        }
    
        static const char* findKey(T value){
            const CStringPair * p = getPairList();
            for (; p->_name[0]!=0; p++)
                if (strcmp(value,p->_value)==0)
                    break;
            return p->_name;
        };
    };
    
    #define DEFINE_PAIRLIST(name, type) struct name:public CStringPairHandle{ \
        static CPair _pairList[];       \
        static CPair* implementation(){     \
            return _pairList;           \
        }};
    #define INIT_PAIRLIST(name) name::CPair name::_pairList[]
    

提交回复
热议问题