繁体   English   中英

将整数格式化为十六进制和十进制

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM