C++:使用 Boost::PFR 遍历 struct 字段的反射
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};
// 像 tuple 一样遍历字段
boost::pfr::for_each_field(p, [](const auto& field, std::size_t i) {
std::cout << "Field #" << i << " = " << field << '\n';
});
return 0;
}输出
reflection_output.txt
Field #0 = 42
Field #1 = Alice
Field #2 = 98.7按类别查看类似文章:
C/C++
如果这篇文章对您有帮助,请考虑请我喝杯咖啡或通过 PayPal 捐款,以支持 TechOverflow 上新文章的研究与发布