What would be a C++17 idiomatic way to implement NaN arithmetic for int-like types? In particular, adding (or subtracting) when either argument is NaN should yield exactly NaN.
(The standard explicitly excludes ints from such default behavior. Even quiet_NaN
returns zero, too dangerous for everyday use.)
My starting point is a value sufficiently out of bounds for my application,
constexpr int my_NaN = std::numeric_limits<int>::max();
In C, you'd replace each x + y
with a my_add(x, y)
which tests x and y against my_NaN. Ugly.
In Ruby, you might monkeypatch the class Integer with def +(other) self==my_NaN ? my_NaN : ...
, and blithely x + y
as usual.
Can C++17 come close to how Ruby lets you preserve conventional infix notation?
Besides a bare int, I'm also hoping to do this for
std::chrono::duration<int64_t, std::micro>
and the corresponding time_point
. I shudder at overriding all the different ways those can be added and subtracted.