String to enum in C++

后端 未结 10 1651
渐次进展
渐次进展 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:52

    You can set up a map that you can use over and over:

    template 
    class EnumParser
    {
        map  enumMap;
    public:
        EnumParser(){};
    
        T ParseSomeEnum(const string &value)
        { 
            map ::const_iterator iValue = enumMap.find(value);
            if (iValue  == enumMap.end())
                throw runtime_error("");
            return iValue->second;
        }
    };
    
    enum SomeEnum
    {
        Value1,
        Value2
    };
    EnumParser::EnumParser()
    {
        enumMap["Value1"] = Value1;
        enumMap["Value2"] = Value2;
    }
    
    enum OtherEnum
    {
        Value3, 
        Value4
    };
    EnumParser::EnumParser()
    {
        enumMap["Value3"] = Value3;
        enumMap["Value4"] = Value4;
    }
    
    int main()
    {
        EnumParser parser;
        cout << parser.ParseSomeEnum("Value2");
    }
    

提交回复
热议问题