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

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

    For C++17 C++20, you will be interested in the work of the Reflection Study Group (SG7). There is a parallel series of papers covering wording (P0194) and rationale, design and evolution (P0385). (Links resolve to the latest paper in each series.)

    As of P0194r2 (2016-10-15), the syntax would use the proposed reflexpr keyword:

    meta::get_base_name_v<
      meta::get_element_m<
        meta::get_enumerators_m,
        0>
      >
    

    For example (adapted from Matus Choclik's reflexpr branch of clang):

    #include 
    #include 
    
    enum MyEnum { AAA = 1, BBB, CCC = 99 };
    
    int main()
    {
      auto name_of_MyEnum_0 = 
        std::meta::get_base_name_v<
          std::meta::get_element_m<
            std::meta::get_enumerators_m,
            0>
        >;
    
      // prints "AAA"
      std::cout << name_of_MyEnum_0 << std::endl;
    }
    

    Static reflection failed to make it into C++17 (rather, into the probably-final draft presented at the November 2016 standards meeting in Issaquah) but there is confidence that it will make it into C++20; from Herb Sutter's trip report:

    In particular, the Reflection study group reviewed the latest merged static reflection proposal and found it ready to enter the main Evolution groups at our next meeting to start considering the unified static reflection proposal for a TS or for the next standard.

提交回复
热议问题