Reflection in C++26: Metafunctions for Enums and Classes

Today, I continue my journey through reflection in C++26 and play with enums and classes.

The names of the metafunctions to access an Enum or a Class member are often identical.

Access the Members of an Enum

The following program is based on one by Daveed Vandevoorde. Daveed is one of the fathers of reflection, and he used this example in his presentation, “Reflections on C++ Reflection.

The program iterates through an Enum and displays its name and value for each enumerator.

// daveed.cpp

#include <array>
#include <experimental/meta>
#include <iostream>

template<typename E> 
struct enum_item { 
  std::string_view name; 
  E value;
};

template<typename E> 
consteval auto get_enum_data() {
  std::array<enum_item<E>, std::meta::enumerators_of(^E).size()> result;
  int k = 0;
  for (auto mem: std::meta::enumerators_of(^E))
    result[k++] = enum_item<E>{ std::meta::identifier_of(mem), std::meta::extract<E>(mem) };
  return result;
}

enum MyEnum { 
  x, 
  y, 
  e = -1, 
  z = 99 
};

int main() {

  std::cout << '\n';

  std::cout << "members of " << std::meta::identifier_of(^MyEnum) << '\n';
  for (auto x: get_enum_data<MyEnum>()) {
    std::cout << "  " << x.name << " = " << (long)x.value << '\n';
  }

  std::cout << '\n';

}

The provided code snippet demonstrates the use of experimental metaprogramming features in C++ to introspect and manipulate enumeration types at compile time. The code begins by including the necessary headers: <array> for array support, <experimental/meta> for metaprogramming utilities, and <iostream> for input-output operations.

The enum_item struct template is defined to hold information about an enumeration item. It contains two members: name, a std::string_view representing the name of the enumerator, and value, which holds the enumerator’s value of type E.

The get_enum_data function template is marked as consteval, meaning it is evaluated at compile time. This function generates an array of enum_item structs for a given enumeration type E. It uses the std::meta::enumerators_of function to retrieve the enumerators of the enumeration type and iterates over them. For each enumerator, it creates an enum_item with the enumerator’s name and value, using std::meta::identifier_of to get the name and std::meta::extract to get the value. The resulting array is then returned.

The MyEnum enumeration is defined with four enumerators: x, y, e (explicitly set to -1), and z (explicitly set to 99). This enumeration is used as an example to demonstrate the metaprogramming capabilities.

In the main function, the code first prints a newline for formatting purposes. It then prints the name of the enumeration type MyEnum using std::meta::identifier_of. Next, it calls get_enum_data<MyEnum>() to retrieve the array of enum_item structs for MyEnum and iterates over this array. For each enum_item, it prints the name and value of the enumerator. The value is cast to long for consistent output formatting. Finally, another newline is printed for formatting.

Overall, this code showcases how compile-time reflection can be used to introspect enumeration types and generate useful metadata, such as enumerator names and values, which can then be used at runtime.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    Here’s the output of the program:

    My Small Experiment

    This explanation was created by Microsoft’s KI tool Copilot. Honestly, I was pretty impressed because the feature I described are brand new.

    Access the Members of a Class

    The following program shows two ways to access the members of a class: by index and name.

    // reflectionClass.cpp
    
    #include <experimental/meta>
    #include <iostream>
    
    struct Base { 
        int i{}; 
        void inc(int& j){ j++; }
    };
    
    consteval auto number(int n) {
      //return std::meta::nonstatic_data_members_of(^Base)[n];
      return std::meta::members_of(^Base)[n];
    }
    
    
    consteval auto named(std::string_view name) {
      for (std::meta::info field : std::meta::members_of(^Base)) {
        if (std::meta::has_identifier(field) && std::meta::identifier_of(field) == name)
          return field;
      } 
      return std::meta::info{};
    }
    
    
    int main() { 
    
      std::cout << '\n';
    
      Base base;
      base.[:number(0):] = 1;  
      // base.[:member_number(10):] = 1;  Error
      std::cout << "base.i= " << base.i << '\n';
      base.[:number(1):](base.i);
      std::cout << "base.i= " << base.i << '\n';
    
      std::cout << '\n';
     
      base.[:named("i"):] = 3;
      std::cout << "base.i= " << base.i << '\n';
      base.[:named("inc"):](base.i);
      std::cout << "base.i= " << base.i << '\n';
    
    }
    

    Base is the class I want to reflect on. The metafunctions number and named provide me the necessary information.

    • number: std::meta::members_of(^Base)[n] returns the member n of Base. On the contrary, number: std::meta::nonstatic_data_members_of(^Base)[n] returns the non-static data member n of Base. The reflection library also has a metafunction for getting all static data members of a class: std::meta::static_data_members_of(^Base)[n]
    • named: iterates through all members of Base and returns the member with the name name: std::meta::identifier_of(field) == name

    Let me jump to the main program. The member i of Base is incremented. Either by assigning the value or invoking the memberfunction inc. Using the wrong index or name gives a compile-time error:[:member_number(10):] = 1)

    Finally, here’s the output of the program.

    What’s Next?

    In my next post, I continue to play with reflection in C++26.

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,