I found a bug in the codebase I'm working in where they check for equality of two doubles (first, second) using first == second, but these 2 variables could be NaN.
If both variables were NaN the equality would be false.
So my current solution is instead of
first == second
we use
(first == second || (std::isnan(first) && std::isnan(second))
Is there a simpler way to do this?
First, evaluate that you actually want the condition to run if both values are NaN. NaN is a good indicator that things went terribly wrong, not a null or empty state. If the intention was to have two values that may or may not exist, you might consider changing them to
std::optional<double>to make that clear. Otherwise, if you are certain, then what you've done is correct. There's no magic trick to making NaN comparisons work, and even if you did find a library that abstracted this away, it would still do exactly what you just did under the hood.