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
相关产品推荐
相关产品推荐

