自定义类型格式化器
什么是自定义格式化器
std::format 默认支持基本类型(整数、浮点数、字符串、bool、指针等)的格式化。对于用户自定义的类型(如结构体、类),需要特化 std::formatter 模板来告诉格式化库如何处理这些类型。
一个 std::formatter 特化需要提供两个成员函数:
parse():解析格式说明符(冒号后面的部分,如{:x}中的x)format():将对象格式化为输出
基本示例
#include <iostream>
#include <format>
#include <string>
#include <vector>
// ============================
// 示例1:最简单的自定义格式化器
// ============================
struct Point {
double x, y;
};
// 为 Point 类型特化 std::formatter
template<>
struct std::formatter<Point> {
// 解析格式说明符——这里不需要特殊格式,直接返回
constexpr auto parse(std::format_parse_context& ctx) {
return ctx.begin();
}
// 格式化 Point 对象
auto format(const Point& p, std::format_context& ctx) const {
return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
}
};
void basic_demo() {
Point p{3.14, 2.71};
std::cout << std::format("点: {}", p) << std::endl;
// 输出: 点: (3.14, 2.71)
// 可以和其他参数混用
std::cout << std::format("从 {} 到 {}", Point{0, 0}, Point{1, 1}) << std::endl;
// 输出: 从 (0, 0) 到 (1, 1)
}
// ============================
// 示例2:继承已有格式化器
// ============================
struct UserId {
unsigned int value;
};
// 继承 int 的格式化器——直接复用整数的格式选项
template<>
struct std::formatter<UserId> : std::formatter<unsigned int> {
auto format(const UserId& id, std::format_context& ctx) const {
// 先输出前缀,再用继承的格式化器输出数字部分
ctx.advance_to(std::format_to(ctx.out(), "User#"));
return std::formatter<unsigned int>::format(id.value, ctx);
}
};
void inherit_demo() {
UserId id{42};
// 可以使用整数的所有格式选项
std::cout << std::format("用户: {}", id) << std::endl; // User#42
std::cout << std::format("用户: {:06}", id) << std::endl; // User#000042
std::cout << std::format("用户: {:x}", id) << std::endl; // User#2a
}
// ============================
// 示例3:支持自定义格式选项
// ============================
struct Color {
uint8_t r, g, b;
};
template<>
struct std::formatter<Color> {
char presentation = 'd'; // 默认十进制,'x' 为十六进制
constexpr auto parse(std::format_parse_context& ctx) {
auto it = ctx.begin();
auto end = ctx.end();
// 检查是否有自定义格式选项
if (it != end && (*it == 'd' || *it == 'x')) {
presentation = *it;
++it;
}
// 必须以 '}' 结束
if (it != end && *it != '}') {
throw std::format_error("Color 格式无效");
}
return it;
}
auto format(const Color& c, std::format_context& ctx) const {
if (presentation == 'x') {
// 十六进制格式: #RRGGBB
return std::format_to(ctx.out(), "#{:02x}{:02x}{:02x}",
c.r, c.g, c.b);
} else {
// 十进制格式: rgb(R, G, B)
return std::format_to(ctx.out(), "rgb({}, {}, {})",
c.r, c.g, c.b);
}
}
};
void custom_spec_demo() {
Color red{255, 0, 0};
Color sky{135, 206, 235};
// 默认格式(十进制)
std::cout << std::format("红色: {}", red) << std::endl;
// 输出: 红色: rgb(255, 0, 0)
// 十六进制格式
std::cout << std::format("红色: {:x}", red) << std::endl;
// 输出: 红色: #ff0000
std::cout << std::format("天蓝: {:x}", sky) << std::endl;
// 输出: 天蓝: #87ceeb
}
// ============================
// 示例4:继承 string 格式化器
// ============================
enum class LogLevel { Debug, Info, Warning, Error };
template<>
struct std::formatter<LogLevel> : std::formatter<std::string> {
auto format(LogLevel level, std::format_context& ctx) const {
std::string name;
switch (level) {
case LogLevel::Debug: name = "DEBUG"; break;
case LogLevel::Info: name = "INFO"; break;
case LogLevel::Warning: name = "WARNING"; break;
case LogLevel::Error: name = "ERROR"; break;
}
// 使用 string 格式化器——支持对齐、宽度等
return std::formatter<std::string>::format(name, ctx);
}
};
void enum_demo() {
std::cout << std::format("[{}] 消息内容", LogLevel::Info) << std::endl;
// 输出: [INFO] 消息内容
// 可以使用 string 的格式选项
std::cout << std::format("[{:>10}] 错误", LogLevel::Error) << std::endl;
// 输出: [ ERROR] 错误
std::cout << std::format("[{:*^10}] 警告", LogLevel::Warning) << std::endl;
// 输出: [*WARNING**] 警告
}
// ============================
// 示例5:复合类型格式化
// ============================
struct Student {
std::string name;
int age;
double gpa;
};
template<>
struct std::formatter<Student> {
char style = 'n'; // 'n' 普通, 'j' JSON风格
constexpr auto parse(std::format_parse_context& ctx) {
auto it = ctx.begin();
if (it != ctx.end() && (*it == 'n' || *it == 'j')) {
style = *it;
++it;
}
return it;
}
auto format(const Student& s, std::format_context& ctx) const {
if (style == 'j') {
return std::format_to(ctx.out(),
R"({{"name": "{}", "age": {}, "gpa": {:.2f}}})",
s.name, s.age, s.gpa);
} else {
return std::format_to(ctx.out(),
"{} (age {}, GPA {:.2f})",
s.name, s.age, s.gpa);
}
}
};
void compound_demo() {
Student s{"Alice", 20, 3.85};
std::cout << std::format("学生: {}", s) << std::endl;
// 输出: 学生: Alice (age 20, GPA 3.85)
std::cout << std::format("学生: {:j}", s) << std::endl;
// 输出: 学生: {"name": "Alice", "age": 20, "gpa": 3.85}
}
// ============================
// 示例6:模板格式化器
// ============================
template<typename T>
struct Wrapper {
T value;
};
// 为模板类型特化格式化器
template<typename T>
struct std::formatter<Wrapper<T>> : std::formatter<T> {
auto format(const Wrapper<T>& w, std::format_context& ctx) const {
ctx.advance_to(std::format_to(ctx.out(), "["));
ctx.advance_to(std::formatter<T>::format(w.value, ctx));
return std::format_to(ctx.out(), "]");
}
};
void template_demo() {
Wrapper<int> wi{42};
Wrapper<double> wd{3.14};
Wrapper<std::string> ws{"hello"};
std::cout << std::format("int: {}", wi) << std::endl; // [42]
std::cout << std::format("double: {:.2f}", wd) << std::endl; // [3.14]
std::cout << std::format("string: {}", ws) << std::endl; // [hello]
}
int main() {
std::cout << "=== 基本格式化器 ===" << std::endl;
basic_demo();
std::cout << "\n=== 继承格式化器 ===" << std::endl;
inherit_demo();
std::cout << "\n=== 自定义格式选项 ===" << std::endl;
custom_spec_demo();
std::cout << "\n=== 枚举格式化 ===" << std::endl;
enum_demo();
std::cout << "\n=== 复合类型 ===" << std::endl;
compound_demo();
std::cout << "\n=== 模板类型 ===" << std::endl;
template_demo();
return 0;
}formatter 特化的结构
template<>
struct std::formatter<YourType> {
// 1. parse:解析格式说明符({: 后面的内容)
constexpr auto parse(std::format_parse_context& ctx) {
// ctx.begin() 指向格式说明符的开始
// ctx.end() 指向 '}' 或格式字符串末尾
// 返回指向已解析末尾的迭代器
return ctx.begin();
}
// 2. format:将对象格式化为文本输出
auto format(const YourType& obj, std::format_context& ctx) const {
// 用 std::format_to(ctx.out(), ...) 输出
// 返回输出迭代器
return std::format_to(ctx.out(), "...");
}
};三种实现策略对比
| 策略 | 做法 | 适合场景 |
|---|---|---|
| 从零实现 | 手写 parse 和 format | 需要完全自定义格式选项 |
| 继承已有格式化器 | 继承 formatter<int> 等 | 主要数据是单个基本类型 |
继承 formatter<string> | 转换为字符串后格式化 | 对齐、宽度等选项自动继承 |
适用场景
- 让自定义类型可以直接用
std::format/std::println - 为枚举类型提供可读的名称输出
- 支持多种格式(如十进制/十六进制颜色)
- 模板类型的通用格式化
- 日志系统中的自定义类型输出
常见问题
parse 函数必须做什么?
parse 必须返回一个迭代器,指向格式说明符中已解析部分的下一个位置。最简单的情况下(不支持任何格式选项),直接返回 ctx.begin() 即可。如果需要自定义格式选项,需要解析并存储到成员变量中。
format 函数为什么要是 const?
C++23 要求 format 函数是 const 成员函数。这保证了格式化操作不会修改格式化器的状态,使其可以被多次安全调用。
继承已有格式化器有什么好处?
继承已有格式化器(如 formatter<int> 或 formatter<string>)可以自动获得该类型支持的所有格式选项(对齐、宽度、精度等),不需要自己解析这些选项。
C++23 对范围的格式化支持是怎样的?
C++23 增加了 std::range_formatter 和 std::format_kind 枚举,标准容器和范围可以直接用 std::format("{}", vec) 格式化。
注意事项
format函数必须是 const 成员函数parse的返回值必须指向已解析内容的下一个位置- 使用
ctx.advance_to()更新输出迭代器位置 - 格式说明符无效时应抛出
std::format_error - 继承格式化器时注意调用基类的 parse
- 模板类型的格式化器需要偏特化
总结
自定义 std::formatter 特化是让用户类型融入 C++20 格式化体系的标准方式。最简单的实现只需要提供 parse 和 format 两个函数,parse 解析格式说明符,format 将对象转为文本。对于简单类型,可以继承已有的 formatter<int> 或 formatter<string> 来复用格式选项。对于需要多种显示格式的类型(如颜色的十进制/十六进制),可以在 parse 中解析自定义选项并存储到成员变量中。一旦定义了格式化器,自定义类型就可以在 std::format、std::print、std::println 中像基本类型一样使用。