samedi 11 novembre 2023

How does boost pfr get the names of fields of a struct?

In Boost 1.84 (currently in progress):

Big new feature: field names reflection. Added new constexpr boost::pfr::get_name<N, T>() function that returns a std::string_view with a name of field at index N of an aggregate T. Requires C++20.

Using the latest version of pfr on github, you can write code like

#include <boost/pfr/core.hpp>
#include <boost/pfr/core_name.hpp>

struct S
{
    int i = 1;
    double d = 2;
    std::string s = "three";
};

const S s;
constexpr auto names = boost::pfr::names_as_array<S>();
boost::pfr::for_each_field(
    s,
    [&names](const auto& field, std::size_t idx)
    { std::cout << idx << ": " << names[idx] << " = " << field << '\n'; });

Output:

0: i = 1
1: d = 2
2: s = three

How does this work? This blog post explains how aggregate initialization can be repurposed to get the fields, but getting the field names seems like magic! But I get the above output on the big three compilers (latest Visual C++, gcc 13.2, clang 16). I'm no wiser looking at the code in core_name20_static.hpp.





Aucun commentaire:

Enregistrer un commentaire