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

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.

?

Modernes C++ Mentoring

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.

Anand Rathi

C++/CUDA/Qt Developer

1 个月

Will be very useful for gaming engines .

回复
Konstantin Grudnev

Senior Software developer C/C++/Python (Linux, Embedded Linux, Highload)

1 个月

It would be great if they decide to remove keyword auto, looking at code where you define auto variables you can see, that using auto all over the place and simple rule can be applied, if variable doesn't have type specified, imply it's an auto and deduct type from assigned value and as with auto, those vars must be initialized.

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了