Can Boost.Pfr be used to iterate the fields of a type as member pointers?

Viewed 56

I know that Boost.Pfr can be used to iterate the fields of a type, and visit them as a T&, but since T& can't be cast to T A::*, I'm wondering if there's something in the library I missed that can allow visiting fields as member pointers.

#include <boost/pfr.hpp>

struct A {
    int number;
    string text;
};

int main() {
    boost::pfr::for_each_field(A{1,"foo"},
        [](auto A::* field) { // wish this or something similar were possible
            
        }
    );
}
1 Answers

PFR doesn't have this (yet?) but if you have recent enough Boost, Describe could be what you're after.

Note it isn't as auto-magic as with PFR, but it does give you the member-pointer information to work with at compile time.

In their "Universal Print Example" you can see that the member descriptor object contains a member pointer which is of pointer-to-member type:

using Md = describe_members<T, mod_any_access>; // for exposition

boost::mp11::mp_for_each<Md>([&](auto D){

    if( !first ) { os << ", "; } first = false;

    os << "." << D.name << " = " << t.*D.pointer;

});
Related