I have the following function:
template <typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int> = 0>
constexpr Float inf2nan(Float x)
{
static_assert(std::numeric_limits<Float>::is_iec559);
return x * 0 + x;
}
This function will return NaN
if the input is infinity, otherwise just the input.
Unfortunately, using the -ffast-math
flag with GCC optimizes this away to just a ret
statement. I want my function to do the same with these flags enabled.
I've also tried replacing it with:
return std::isinf(x) ? std::numeric_limits<Float>::quit_NaN() : x;
but this does not get optimized by GCC and clang to the same output as my original function.
Is there a way (via comment or macro) to enable strict floating point math for just a single variable or function similar to Java's strictfp
keyword with GCC and clang? Alternatively, can I detect that fast math was enabled in my code and conditionally compile the latter version?