String to enum in C++

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

    Using a std::map raises the question: how does the map get initialised? I would rather use a function:

    enum E { A, B };
    
    E f( const std::string & s ) {
       if ( s == "A" ) {
          return A;
        }
        else if ( s == "B" ) {
          return B;
        }
        else {
          throw "Your exception here";
        }
    }
    
    0 讨论(0)
  • 2020-11-28 07:35

    Parse the string yourself, match the string with a value (which is also an index to a map<string, enum>.

    0 讨论(0)
  • 2020-11-28 07:36
    std::map< string, enumType> enumResolver;
    
    0 讨论(0)
  • 2020-11-28 07:51

    I agree with many of the answers that std::map is the easiest solution.

    If you need something faster, you can use a hash map. Perhaps your compiler already offers one, such as hash_map or the upcoming standard unordered_map, or you can get one from boost. When all the strings are known ahead of time, perfect hashing can be used as well.

    0 讨论(0)
  • 2020-11-28 07:52

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

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

    Look at Boost.Bimap, it provides bidirectional associations between two sets of values. You can also choose the underlying container.

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