You need to enable JavaScript to run this app. 模板化fmt::formatter特化遇编译错误,求自定义类型格式化方案
优惠活动
大模型
产品
解决方案
定价
更多

模板化fmt::formatter特化遇编译错误,求自定义类型格式化方案

问题:让重载operator std::string()的类型支持fmt格式化

原始工作代码

原本为单个自定义类型实现fmt格式化的代码可以正常运行:

#include "fmt/format.h"

struct MyClass
{
    operator std::string() const
    {
        return "xyz";
    }
};

template <> struct fmt::formatter<MyClass>
{
    template <typename ParseContext> constexpr auto parse(ParseContext& ctx) const {
        return ctx.begin();
    }
    template <typename FormatContext> constexpr auto format(const MyClass& c, FormatContext& ctx) const {
        return format_to(ctx.out(), "{}", (std::string)c);
    }
};

尝试的错误写法及编译错误

为了复用逻辑给所有能转成std::string的类型,用户尝试模板化该特化,但写法错误:

template <typename T> template <> struct fmt::formatter<T>
{
    template <typename ParseContext> constexpr auto parse(ParseContext& ctx) const {
        return ctx.begin();
    }
    template <typename FormatContext> constexpr auto format(const T& t, FormatContext& ctx) const {
        return format_to(ctx.out(), "{}", (std::string)t);
    }
};

template struct fmt::formatter<MyClass>;

编译报错:

error C2913: explicit specialization; 'fmt::v7::formatter<MyClass,char,void>' is not a specialization of a class template

解决方案

方法一:正确实现通用偏特化

fmt的formatter主模板实际包含三个参数(带默认值):template <typename T, typename Char = char, typename Enable = void> struct formatter;。我们可以通过偏特化为所有可转换为std::string的类型提供通用实现,复用std::string的formatter逻辑:

#include "fmt/format.h"
#include <string>
#include <type_traits>

// 偏特化fmt::formatter,为所有可隐式转成std::string的类型提供格式化支持
template <typename T, typename Char>
struct fmt::formatter<T, Char, std::enable_if_t<std::is_convertible_v<T, std::string>>>
    : fmt::formatter<std::basic_string<Char>, Char> {
    // 复用基类的parse方法,无需重写
    template <typename FormatContext>
    auto format(const T& t, FormatContext& ctx) const {
        // 将T转换为std::string后,交给基类的format处理
        return fmt::formatter<std::basic_string<Char>, Char>::format(static_cast<std::string>(t), ctx);
    }
};

// 测试类型
struct MyClass {
    operator std::string() const { return "xyz"; }
};

// 按需实例化(可选,模板会自动按需实例化)
template struct fmt::formatter<MyClass>;

方法二:更简便的方式——使用fmt::format_as

fmt提供了format_as钩子函数,只需定义该函数即可让类型自动支持格式化,无需手动特化formatter:

#include "fmt/format.h"
#include <string>
#include <type_traits>

struct MyClass {
    operator std::string() const { return "xyz"; }
};

// 为所有可转成std::string的类型定义format_as
template <typename T>
auto format_as(const T& t) -> std::enable_if_t<std::is_convertible_v<T, std::string>, std::string> {
    return static_cast<std::string>(t);
}

错误原因说明

原代码的写法template <typename T> template <> struct fmt::formatter<T>是语法错误:C++不允许在模板内部嵌套显式特化。正确的做法是针对fmt::formatter的主模板做偏特化,而非尝试创建“模板化的显式特化”。

内容的提问来源于stack exchange,提问作者H.v.M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 06:23:14