Boost.PFR如何获取结构体字段名称?实现原理探究
Boost PFR 聚合类型字段名称反射的实现原理
Boost 1.84版本(当前处于开发阶段)将新增一项重大特性:聚合类型字段名称反射。新增的constexpr函数boost::pfr::get_name<N, T>()可返回聚合类型T中第N个字段名称的std::string_view,该特性依赖C++20标准。
使用最新版Boost PFR可编写如下示例代码:
#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'; } );
运行代码后输出结果为:
0: i = 1 1: d = 2 2: s = three
这一特性的实现原理是什么?有文章曾解释过如何通过聚合初始化获取字段值,但字段名称的获取方式却显得十分“神奇”!尽管这段代码能在最新版Visual C++、GCC 13.2、Clang 16三大主流编译器上正常运行,但即便查看Boost PFR源码里的core_name20_static.hpp文件,也很难搞懂它的实现逻辑。
内容的提问来源于stack exchange,提问作者TooTone
相关产品推荐
相关产品推荐

