命名空间
变体
操作

std::saturate_cast

来自 cppreference.cn
< cpp‎ | numeric
定义于头文件 <numeric>
template< class T, class U >
constexpr T saturate_cast( U x ) noexcept;
(自 C++26 起)

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

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

内容

[edit] 参数

x - 一个整数值

[edit] 返回值

  • x,如果 x 可以表示为 T 类型的值。 否则,
  • T 类型最大或最小的可表示值,以更接近 x 的值为准。

[edit] 注解

特性测试 Std 特性
__cpp_lib_saturation_arithmetic 202311L (C++26) 饱和算术

[edit] 可能的实现

参见 libstdc++ (GCC)

[edit] 示例

可以在 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);
}

[edit] 参见

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