enum to string in modern C++11 / C++14 / C++17 and future C++20

后端 未结 28 2321
逝去的感伤
逝去的感伤 2020-11-22 16:57

Contrary to all other similar questions, this question is about using the new C++ features.

  • 2008 c Is there a simple way to convert C++ enum to string?
  • <
28条回答
  •  无人共我
    2020-11-22 17:20

    If your enum looks like

    enum MyEnum
    {
      AAA = -8,
      BBB = '8',
      CCC = AAA + BBB
    };
    

    You can move the content of the enum to a new file:

    AAA = -8,
    BBB = '8',
    CCC = AAA + BBB
    

    And then the values can be surrounded by a macro:

    // default definition
    #ifned ITEM(X,Y)
    #define ITEM(X,Y)
    #endif
    
    // Items list
    ITEM(AAA,-8)
    ITEM(BBB,'8')
    ITEM(CCC,AAA+BBB)
    
    // clean up
    #undef ITEM
    

    Next step may be include the items in the enum again:

    enum MyEnum
    {
      #define ITEM(X,Y) X=Y,
      #include "enum_definition_file"
    };
    

    And finally you can generate utility functions about this enum:

    std::string ToString(MyEnum value)
    {
      switch( value )
      {
        #define ITEM(X,Y) case X: return #X;
        #include "enum_definition_file"
      }
    
      return "";
    }
    
    MyEnum FromString(std::string const& value)
    {
      static std::map converter
      {
        #define ITEM(X,Y) { #X, X },
        #include "enum_definition_file"
      };
    
      auto it = converter.find(value);
      if( it != converter.end() )
        return it->second;
      else
        throw std::runtime_error("Value is missing");
    }
    

    The solution can be applied to older C++ standards and it does not use modern C++ elements but it can be used to generate lot of code without too much effort and maintenance.

提交回复
热议问题