Herb Sutter 直接把反射称为“自模板发明以来 C++最大的一次升级”,但要十年时间才会充 分体现出来。 ++26引入编译期反射运算符~^(俗称 'cat-ears”)和新头文件: 、^^T:产生描述类型丁的编译期元对象 (std::meta::info)。 提供一系列 consteval工具函数,比 如: std::meta::members_of(info) std::meta::bases_of(info) std::meta::enumerators_of(info)。

比如这样的: include include int main() constexpr auto r = ^int. typename[:r:] x = 42; typename[:^char:] c ="', static_assert(std::same_as); static_assert(std::same_as); assert(x == 42); assert(c ==''); return 0;

枚举转字符串: include #include template requires std::is_enum_v constexpr std::string enum_to_string(E value) std::string result ="". [:expand(std:meta:: enumerators_of(^E)):] >> [&]{ if (value ==[:e:]){ result = std::meta::identifier_of(e); return result; 字符串转枚举:

template requires std::is_enum_v constexpr std::optional string_to_enum(std::string_view name) < template for (constexpr auto e: std::meta::enumerators_of(^E)){ if (name == std::meta::identifier_of(e)) return [:e:]; } return std::nullopt;

Herb Sutter 直接把反射称为“自模板发明以来 C++最大的一次升级”,但要十年时间才会充 分体现出来。 ++26引入编译期反射运算符~^(俗称 'cat-ears”)和新头文件: 、^^T:产生描述类型丁的编译期元对象 (std::meta::info)。 提供一系列 consteval工具函数,比 如: std::meta::members_of(info) std::meta::bases_of(info) std::meta::enumerators_of(info)。
【瓜分奖池】编译期反射 第5张插图