我正在将一些软件转换为使用fmt库,该库以前使用double-conversion
,iostream
和boost::format
的组合。输出的大多数数值都是双精度浮点数,并且我们有许多测试来检查涉及无穷大,nan等的极端情况。
我的问题是,使用fmt,许多测试输出已经更改为显示负非数字:-nan
,这对我来说是一个完全无意义的概念。
我意识到IEEE-754规范允许nan
s的大量不同的位表示,包括设置或清除符号位。但我想知道的是一个值是否是数字。一旦值是nan
,我不在乎是否有人试图否定该值。对nan
进行任何运算的结果都应该是nan
。负号没有任何意义。
那么在使用libfmt时,我如何省略double
-nan
值上的负号?
我最终为double制作了一个包装器类,并为它定义了一个自定义的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
}
};