C++ reflection: How to iterate over fields of struct using Boost::PFR
reflection_iter_fields.cpp
#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;
}
```plaintext {filename="c-reflection-how-to-iterate-over-fields-of-struct-using-boost-pfr_block2.txt"}
### Output
```plaintext {filename="98.7"}
Field #0 = 42
Field #1 = Alice
Field #2 = 98.7
```plaintext {filename="98.7"}
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow