[英]Format an integer as both hex and decimal
我想向 fmt 添加一個格式說明符來修改整數的格式。 具體來說,我需要以十六進制和十進制的形式打印一個整數,例如以“0xff (256)”的形式。
不過,我似乎只能為自定義類型添加自定義格式化程序。 因此,例如,這樣的事情是行不通的:
using myint = uint64_t;
template <> struct fmt::formatter<myint> {
constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
auto it = ctx.begin(), end = ctx.end();
if(it != end && *it == 'z')
it++;
return it;
}
template <typename FormatContext>
auto format(const myint& p, FormatContext& ctx) const -> decltype(ctx.out()) {
return fmt::format_to(ctx.out(), "z: {:x} {}", p, p);
}
};
即使我將自己限制為特定類型的整數。 還有其他方法嗎?
這樣做的方法是在您的類型中包裝一個整數並為此提供formatter
專業化:
struct myint {
uint64_t value;
};
template <> struct fmt::formatter<myint> {
// ...
};
然后你可以執行fmt::format("{}", myint{42})
並實現你喜歡的任何格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.