跳转至

ev-fmt-optional-formatter-001

字段 值
项目 fmtlib/fmt
固定 commit 1be298e1bd68
路径 include/fmt/std.h
行段 L416-L427
特性 std::optional
许可证 MIT
代码来源 项目源码
级别 manual
审核 zyuhao7 @ 2026-10-24
测试代码 否
发现方式 regex

用法

为空状态输出 none,有值时输出 optional(value)

为什么典型

把可选值的两种状态显式格式化,避免日志里把空状态与默认值混淆。

摘录

  template <typename FormatContext>
  auto format(const std::optional<T>& opt, FormatContext& ctx) const
      -> decltype(ctx.out()) {
    if (!opt) return detail::write<Char>(ctx.out(), none);

    auto out = ctx.out();
    out = detail::write<Char>(out, optional);
    ctx.advance_to(out);
    out = underlying_.format(*opt, ctx);
    return detail::write(out, ')');
  }
};

备注

生产路径;formatter 仅在 __cpp_lib_optional 可用时定义。

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