From cppreference.com
template<classT,classU>constexprTsaturating_cast(Ux)noexcept;(since C++26)Converts the value x to a value of type T, clamping x between the minimum and maximum values of type T.
The program is ill-formed if either T or U is not a signed or unsigned
(including
and
).
Parameters
x - an integer value Return value
x, if x is representable as a value of type T. Otherwise,
either the largest or smallest representable value of type T, whichever is closer to the value of x.
Notes
macro ValueStdFeature
__cpp_lib_saturation_arithmetic
(C++26)Saturation arithmetic
(C++26)Renaming saturation arithmetic functions Possible implementation
See
,
.
Example
Run this code
#include<cstdint>#include<limits>#include<numeric>intmain(){constexprstd::int16_tx1{696};constexprstd::int8_tx2=std::saturating_cast<std::int8_t>(x1);static_assert(x2==std::numeric_limits<std::int8_t>::max());constexprstd::uint8_tx3=std::saturating_cast<std::uint8_t>(x1);static_assert(x3==std::numeric_limits<std::uint8_t>::max());constexprstd::int16_ty1{-696};constexprstd::int8_ty2=std::saturating_cast<std::int8_t>(y1);static_assert(y2==std::numeric_limits<std::int8_t>::min());constexprstd::uint8_ty3=std::saturating_cast<std::uint8_t>(y1);static_assert(y3==0);}See also
(C++20)
reinterpret the object representation of one type as that of another
(function template)
(C++17)
clamps a value between a pair of boundary values
(function template & algorithm function object)
(C++20)
(C++20)
checks if an integer value is in the range of a given integer type
(function template)