在 Boost 1.84 中(目前正在进行中):
重大新功能:字段名称反射。添加了新的 constexpr boost::pfr::get_name
() 函数,该函数返回 std::string_view,其字段名称位于聚合 T 的索引 N 处。需要 C++20。
使用github上的最新版本的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)上得到了上述输出。我并没有更明智地查看 core_name20_static.hpp 中的代码。
boost::typeindex::type_id<T>().pretty_name()
或各种自动“枚举到字符串”。这些使用 __PRETTY_FUNCTION__
/__FUNCSIG__
来获取“美化”函数名称(其中包括完整写出模板参数)。使用它,我们可以获得模板参数的名称:
template<typename T>
void test() {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
template<auto V>
void test() {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
int main() {
test<std::string>();
enum { a };
test<a>();
}
// GCC output
void test() [with T = std::__cxx11::basic_string<char>]
void test() [with auto V = main::a]
您将删除适当的字符以获得您想要的“名称”。
在 C++20 之前,指针/引用非类型模板参数必须指向完整的对象。在 C++20 中,它们现在可以指向子对象。因此,您创建一个对象并指向它:
struct S
{
int i = 1;
double d = 2;
std::string this_is_the_name_we_want = "three";
};
extern S fake_object;
template<auto* P>
void test() {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
int main() {
test<&fake_object.this_is_the_name_we_want>();
}
// GCC output
void test() [with auto* P = (& fake_object.S::this_is_the_name_we_want)]
(您可以使用与
boost::pfr::for_each_field
相同的方法获得每个成员的引用)