带有{fmt}的自定义格式说明符,用于自定义类 [英] Custom format specifier with {fmt} for custom class
本文介绍了带有{fmt}的自定义格式说明符,用于自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
格式化自己的自定义类型时,如何允许自定义填充等?
How would I go about allowing for custom padding, etc.. when formatting my own custom types?
struct S
{
int x;
};
template<> struct fmt::formatter<S> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const S& s, FormatContext& ctx)
{
return format_to(ctx.out(), "{}", s.x);
}
};
S s; s.x = 1;
fmt::format("{:<10}", s); // error
推荐答案
由于您似乎只重用了现有的格式说明符,因此可以将操作转发到 formatter< int>
:
Since you seem to only reuse existing format specifiers, you can just forward operations to formatter<int>
:
template<> struct fmt::formatter<S> {
formatter<int> int_formatter;
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
return int_formatter.parse(ctx);
}
template <typename FormatContext>
auto format(const S& s, FormatContext& ctx)
{
return int_formatter.format(s.x, ctx);
}
};
如果要使用其他语法,或者不想依赖 formatter< int>
,则还可以手动解析 formatter :: parse
.
template<> struct fmt::formatter<S> {
enum { left, right } align = right;
int width = 0;
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx)
{
auto it = ctx.begin();
// parse /align/
if (*it == '<') {
align = left;
++it;
}
// parse /width/
const char* width_str_begin = std::to_address(it);
const char* width_str_bound = std::to_address(ctx.end());
auto [ptr, ec] = std::from_chars(width_str_begin, width_str_bound, width);
auto length = ptr - width_str_begin;
it += length;
// error handling omitted
return it;
}
template <typename FormatContext>
auto format(const S& s, FormatContext& ctx)
{
return format_to(ctx.out(), align == left ? "{:<{}}" : "{:>{}}", s.x, width);
}
};
这篇关于带有{fmt}的自定义格式说明符,用于自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文