c++ 如何禁用fmt中的“-nan”打印

5gfr0r5j  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(129)

我正在将一些软件转换为使用fmt库,以前fmt库使用double-conversioniostreamboost::format的组合,输出的大多数数值是双精度浮点,我们进行了大量测试,检查无穷大、nan等极端情况。
我的问题是,使用fmt时,许多测试输出都变成了显示 negative-not-numbers-nan,这对我来说是一个毫无意义的概念。
我知道IEEE-754规范允许nan的大量不同位表示,包括设置或清除符号位。但我想知道的是一个值是否为数字。一旦一个值为nan,我不在乎是否有人试图对这个值求反,对nan的任何运算结果都应该是nan,负号不会增加任何有意义的值。
那么,在使用libfmt时,如何省略double-nan值上的负号呢?

nimxete2

nimxete21#

我最终为双精度创建了一个 Package 类,并为它定义了一个自定义的formatter,这解决了我遇到的问题。

#include <cmath> // for std::isnan

struct Numeric {
  Numeric() = default;
  Numeric(double d) : value(d) { }
  double value = 0.0;
};

template <> struct fmt::formatter<Numeric> : fmt::formatter<double> {
  // parse function inherited from formatter<double>
  template <typename FormatContext>
  auto format(const Numeric& n, FormatContext& ctx) const -> decltype(ctx.out()) {
    return std::isnan(n.value) ?
      fmt::format_to(ctx.out(), "nan") :       // avoid output of "-nan"
      formatter<double>::format(n.value, ctx); // otherwise use inherited format function
  }
};

相关问题