1

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 also tried replacing it with:

return std::isinf(x) ? std::numeric_limits<Float>::quit_NaN() : x;

but this does not get optimized by the GCC and clang to the same output as my 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?

Jan Schultke
  • 5,808
  • 1
  • 22
  • 57

1 Answers1

3

One way how to do that is to place all function definitions for which you want to have a certain set of compiler flags into on compilation unit (.cpp file) and compile this compilation unit with its own settings. That way you do not need to rely on compiler related in source settings.

How to exactly do that depends on your toolchain. In CMake you could create an OBJECT library, and link that OBJECT library with your executable. In a make file, it should also be straight forward to do that.

For in-source gcc specific solutions there is:

t.niese
  • 36,631
  • 8
  • 65
  • 95