c++reflectionenumsc++26

C++26 Reflection and Loops over enums


Does C++26 reflection proposal include a way to loop through enums?


Solution

  • Language proposal P2996 specifies std::meta::enumerators_of(), enabling us to write something like this when it's adopted:

      template for (constexpr auto e: std::meta::enumerators_of(^E)) {
          auto const v = [:e:];
          // ...
      }
    

    Or more concisely, if range splicers are available:

      for (auto v: [: ...std::meta::enumerators_of(^E) :]) {
          // ...
      }
    

    Although P2996 targets C++26, it doesn't include range splicers as part of the proposal. They may be adopted in a later standard.