C++ reflection: How to iterate over fields of struct using Boost::PFR
#include <boost/pfr.hpp>
#include <iostream>
#include <string>
struct Person {
int id;
std::string name;
double score;
};
int main() {
Person p{42, "Alice", 98.7};
// Iterate over fields like a tuple
boost::pfr::for_each_field(p, [](const auto& field, std::size_t i) {
std::cout << "Field #" << i << " = " << field << '\n';
});
return 0;
}
Output
Field #0 = 42
Field #1 = Alice
Field #2 = 98.7
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow