PAYATHON 2026

C++26 中如何获取注解中的值

数据小陈

结论:别把这个 std::vector 结果存成 constexpr 变量。std::meta::annotations_of_with_type 返回 std::vector<std::meta::info>,而 std::meta::info 是 consteval-only 类型。把 vector 存成 constexpr 变量,常量求值期间由 operator new 产生的分配就得活到变量初始化之后,GCC 会在这里报错。更稳妥的做法是在一次常量求值里把这个 vector 用完,或者把它包进 consteval 函数,只把最终需要的值返回出来。

原因

  • annotations_of_with_type(^^T, ^^HasTag) 返回 std::vector<std::meta::info>。
  • std::vector 的存储要动态分配;常量求值里的分配只能在该次求值期间临时存在。
  • 写成 constexpr auto tags = ...,等于要求这个 vector 本身成为 constexpr 变量。分配不能跨出常量求值,所以会出现 operator new 相关错误。
  • 去掉 constexpr 后,std::meta::info 这类 consteval-only 值又会落到非持续求值上下文里,编译器于是要求把 constexpr 加回来。

推荐写法:用 consteval 辅助函数立即消费

只返回最终需要的 std::string_view 或 const char*,别让 std::vector 变量离开常量求值:

#include <print>
#include <meta>
#include <string_view>

using namespace std::meta;

struct HasTag {
    const char* tag;
};

struct [[=HasTag{"abc"}]] Tagged { int unused; };

template<typename T>
consteval std::string_view get_last_tag() {
    auto tags = annotations_of_with_type(^^T, ^^HasTag);
    if (tags.empty()) {
        return "no tags";
    }
    return extract<HasTag>(tags.back()).tag;
}

template<typename T>
void print_tag(T&&) {
    std::print("{}", get_last_tag<T>());
}

int main() {
    print_tag(Tagged{});
    std::println("");
}

tags 只存在于 get_last_tag 的常量求值内部。函数返回时 vector 已经析构,不会留下持久的常量分配。

如果只想在 if constexpr 中判断

也可以把判断放进 consteval 函数,这样模板里就不用声明 constexpr auto tags:

template<typename T>
consteval bool has_tag() {
    return !annotations_of_with_type(^^T, ^^HasTag).empty();
}

template<typename T>
void print_tag(T&&) {
    if constexpr (has_tag<T>()) {
        std::print("{}", extract<HasTag>(
            annotations_of_with_type(^^T, ^^HasTag).back()).tag);
    } else {
        std::print("no tags");
    }
}

注意:上面那段代码里的 annotations_of_with_type(...).back() 仍然是在一次常量表达式里使用临时 vector。如果某个编译器版本对“临时对象跨出 immediate invocation”的检查更严格,优先用前一种 consteval 辅助函数写法。

需要保留整个注解数组时

如果你确实要在运行时保留所有注解,不要声明 constexpr std::vector。可以用实现提供的静态化设施把结果物化成静态数组或字符串,比如 define_static_array(具体命名空间和可用性以你的 GCC 版本为准):

constexpr auto tags = std::define_static_array(
    annotations_of_with_type(^^T, ^^HasTag)
);

不过,这会把整个数组固化到静态存储中,通常比只取最后一个元素更重。就当前问题来说,直接返回 std::string_view 的 consteval 辅助函数已经够用。

注意事项

  • 确认编译器支持 C++26 反射,并打开对应标准选项。C++26 反射还在实现推进中,GCC 不同小版本的 API 和诊断可能不一样。
  • extract<HasTag>(...).tag 返回的指针指向注解里的字符串字面量时,具有静态存储期,转成 std::string_view 是安全的;如果注解里存的是运行期指针,就不能这样跨出常量求值使用。
  • 不要在需要运行时值的路径上写 constexpr auto tags = annotations_of_with_type(...)。把消费逻辑放进 consteval 函数,是最稳妥的模式。

备注:内容仅供参考。