You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何使用spdlog打印自定义类的std::unique_ptr指针?

问题根因
  • 你仅实现了const my_type*类型的输出运算符重载,未对std::unique_ptr<my_type>做适配,spdlog依赖的fmt库无法识别该类型的格式化规则
  • std::unique_ptr是不可拷贝类型,默认参数处理逻辑尝试触发拷贝构造函数(该函数已被标准库声明为删除),直接导致编译失败
解决方案

两种方案可选,都可以保留你原有的调用写法不变:

方案1:新增std::unique_ptr<my_type>的输出运算符重载

在你的my_type结构体定义后添加如下代码即可:

template<typename OStream>
OStream &operator<<(OStream &os, const std::unique_ptr<my_type>& ptr)
{
    // 直接复用你已经写好的const my_type*的输出逻辑
    return os << ptr.get();
}

该方案无需修改原有其他逻辑,适配成本最低。

方案2:为fmt库特化std::unique_ptr<my_type>的格式化器

如果不想新增全局的输出运算符重载,可以直接针对fmt库做特化适配:

template<>
struct fmt::formatter<std::unique_ptr<my_type>> : fmt::formatter<std::string> {
    auto format(const std::unique_ptr<my_type>& ptr, format_context& ctx) const {
        if (!ptr) {
            return formatter<std::string>::format("[my_type (nullptr)]", ctx);
        }
        return formatter<std::string>::format(fmt::format("[my_type i={}]", ptr->i), ctx);
    }
};

该方案不会污染全局的运算符重载,仅对fmt/spdlog的格式化逻辑生效。

内容的提问来源于stack exchange,提问作者R. N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:09:04