跳转至

ev-fmt-consteval-format-string-003

字段 值
项目 fmtlib/fmt
固定 commit 1be298e1bd68
路径 include/fmt/base.h
行段 L2698-L2709
特性 consteval 与 constinit
许可证 MIT
代码来源 项目源码
级别 manual
审核 zyuhao7 @ 2026-10-26
测试代码 否
发现方式 manual

用法

用 consteval 构造函数在编译期校验格式串

为什么典型

格式串检查必须在编译期完成;立即函数保证构造函数只在常量求值中可用,运行期字符串无法绕过检查。

摘录

  // Reports a compile-time error if S is not a valid format string for T.
  template <size_t N>
  FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) {
    using namespace detail;
    static_assert(count<(is_view<remove_cvref_t<T>>::value &&
                         std::is_reference<T>::value)...>() == 0,
                  "passing views as lvalues is disallowed");
    if (FMT_USE_CONSTEVAL)
      parse_format_string<char>(str, checker(str, arg_pack()));
    constexpr bool unused = detail::enforce_compile_checks<sizeof(s) != 0>();
    (void)unused;
  }

备注

生产头文件;FMT_CONSTEVAL 在 C++20 下展开为 consteval。

查看固定 commit 源码 · 返回证据索引