format

  • format只支持编译器字符串常量,因此,如果字符串是变的话,就要使用vformat。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <format>
#include <iostream>
struct Frac {
int a, b;
};
///通过特化formatter就能在format的时候使用自定义类型了
template <>
struct std::formatter<Frac, char> {
/// 用来解析格式
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
/// 实际格式化,一定要const
template <typename FormatContext>
auto format(const Frac& f, FormatContext& ctx) const {
/// 实际上就是format加上将结果用out_iterator输出
return std::format_to(ctx.out(), "{} / {}", f.a, f.b);
}
};
void print(const char* str, auto&&... args) {
std::cout << std::vformat(str, std::make_format_args(std::forward<decltype(args)>(args)...));
}
int main() {
Frac f{1, 10};
print("{}", f);
}

format
https://lhish.github.io/project/hide/format/
作者
lhy
发布于
2025年8月16日
许可协议