Namespaces
Variants

std:: saturate_cast

From cppreference.net
Saturation arithmetic
Functions
(C++26)
(C++26)
(C++26)
(C++26)
saturate_cast
(C++26)
定义于头文件 <numeric>
template < class T, class U >
constexpr T saturate_cast ( U x ) noexcept ;
(C++26 起)

将值 x 转换为 T 类型,并将 x 钳制在类型 T 的最小值与最大值之间。

如果 T U 不是有符号或无符号的 整数类型 (包括 标准整数类型 扩展整数类型 ),则程序非良构。

目录

参数

x - 整数值

返回值

  • x 可表示为类型 T 的值,则结果为 x 。否则,
  • 结果为类型 T 的最大或最小可表示值,取更接近 x 值的一方。

注释

功能测试 标准 功能
__cpp_lib_saturation_arithmetic 202311L (C++26) 饱和算术

可能的实现

参见 libstdc++ (GCC)

示例

可在 Compiler Explorer 上预览。

#include <cstdint>
#include <limits>
#include <numeric>
int main()
{
    constexpr std::int16_t x1{696};
    constexpr std::int8_t x2 = std::saturate_cast<std::int8_t>(x1);
    static_assert(x2 == std::numeric_limits<std::int8_t>::max());
    constexpr std::uint8_t x3 = std::saturate_cast<std::uint8_t>(x1);
    static_assert(x3 == std::numeric_limits<std::uint8_t>::max());
    constexpr std::int16_t y1{-696};
    constexpr std::int8_t y2 = std::saturate_cast<std::int8_t>(y1);
    static_assert(y2 == std::numeric_limits<std::int8_t>::min());
    constexpr std::uint8_t y3 = std::saturate_cast<std::uint8_t>(y1);
    static_assert(y3 == 0);
}

参见

(C++20)
将一种类型的对象表示重新解释为另一种类型的对象表示
(函数模板)
(C++17)
将值限制在一对边界值之间
(函数模板)
(C++20)
检查整数值是否在给定整数类型的范围内
(函数模板)