0

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.

Camille Goudeseune
  • 2,934
  • 2
  • 35
  • 56
  • 9
    Define a specific type (class) `nanable_int` and use that. – 1201ProgramAlarm Oct 10 '21 at 21:17
  • You might even then be able to just use `std::chrono::duration` without having to do anything else – Alan Birtles Oct 10 '21 at 21:32
  • @AlanBirtles, almost. If `t` has that type, then `t.time_since_epoch() / 1us`, the common way to convert back to bare usecs, needs a custom `operator/`. – Camille Goudeseune Oct 10 '21 at 22:19
  • It also needs `operator<`, `operator>`, `operator+`, `operator-`, ... . Drat. – Camille Goudeseune Oct 10 '21 at 22:31
  • Can you just wrap a `double` in a class, and then make sure to floor or ceil or trunc after the appropriate operations? Still has the "all the operators" problem. – Eljay Oct 10 '21 at 23:32
  • 3
    @Elliott • `double` already has NaN behaviors. If an `int` is 32-bit on the OP's platform, a double (presumably IEEE 754) can express 53-bit of positive integers with fidelity, and 53-bit of negative integers. If that 54-ish-bit of range isn't enough, then, yes, a double is not sufficient. – Eljay Oct 11 '21 at 00:38
  • @Elliot • I'm not sure as to what OP's requirement you are referring to. – Eljay Oct 11 '21 at 01:22
  • @Elliott: I interpret that statement as "I tried this approach", not as "this is a hard external requirement how NaN must be represented". I agree with Eljay; using FP types as stand-ins for integers is a well-known technique dating back to at least the Cray computers. – MSalters Oct 11 '21 at 08:35
  • @Elijay, the people have spoken. I've removed my comments. =] – Elliott Oct 11 '21 at 10:47

0 Answers0