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

后端 未结 28 2228
逝去的感伤
逝去的感伤 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:28

    What about a simple streaming overload? You still have to maintain the mapping if you don't want to do some macro magic, but I find it cleaner than your original solution.

    #include   // for std::uint_fast8_t
    #include 
    #include 
    #include 
    
    enum class MyEnum : std::uint_fast8_t {
       AAA,
       BBB,
       CCC,
    };
    
    std::ostream& operator<<(std::ostream& str, MyEnum type)
    {
        switch(type)
        {
        case MyEnum::AAA: str << "AAA"; break;
        case MyEnum::BBB: str << "BBB"; break;
        case MyEnum::CCC: str << "CCC"; break;
        default: break;
        }
        return str;
    }
    
    int main()
    {
       std::cout << MyEnum::AAA <<'\n';
    }
    

提交回复
热议问题