命名空间
变体
操作

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 不是有符号或无符号整数类型(包括标准整数类型扩展整数类型),则程序格式错误。

目录

[编辑] 参数

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)
检查整数值是否在给定整数类型的范围内
(函数模板) [编辑]