C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Adding safe saturated floating-point to integer cast to C++26

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 08 Apr 2025 10:35:06 -0700
On Tuesday, 8 April 2025 10:01:56 Pacific Daylight Time John Platts wrote:
> Implementing optimal std::saturated_cast for float to int conversions
> requires support from the compiler as a generic, portable pure C++
> implementation is suboptimal on many ISA's and as static_cast<int> invokes
> undefined behavior for values that are outside of the range of an int.

That is understood.

The point is that we don't need a Core Language change for this.
std::saturate_cast<Integer>(FP) can be a library function and it can be plain
QoI for the compiler vendors to implement it optimally. That can also allow
the compiler to deal with a -ffinite-math-only build mode, where no NaNs can
happen.

For example:
template <integral To, floating_point From> To saturate_cast(From f)
{
    return __builtin_saturate_cast_fp(f, To(0));
}

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel DCAI Platform & System Engineering

Received on 2025-04-08 17:35:09