跳转至

ev-spdlog-std-format-custom-type-002

字段 值
项目 gabime/spdlog
固定 commit 79524ddd08a4
路径 example/example.cpp
行段 L283-L289
特性 std::format
许可证 MIT
代码来源 项目源码
级别 manual
审核 zyuhao7 @ 2026-10-26
测试代码 否
发现方式 regex

用法

为自定义类型特化 std::formatter 并复用 format_to

为什么典型

项目类型要同时适配 fmt 与 std::format;两个分支提供同名格式化行为,切换后端不改变调用方代码。

摘录

#else  // when using std::format
template <>
struct std::formatter<my_type> : std::formatter<std::string> {
    auto format(my_type my, format_context &ctx) const -> decltype(ctx.out()) {
        return std::format_to(ctx.out(), "[my_type i={}]", my.i);
    }
};

备注

随项目分发的示例代码,不是测试;展示 std::format 后端下的自定义格式化器写法。

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