std::saturate_cast

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

将值 x 转换为 T 类型的值,并使得 x 夹在 T 类型的最小值和最大值之间。

如果 T 或者 U 不是有符号或者无符号整数类型(包括标准整数类型扩展整数类型),则结果未定义。

目录

[编辑]参数

x - 整数

[编辑]返回值

  • x,如果 x 表示 T 类型的值。否则,
  • T 类型的最接近 x 的最大值或者最小值。

[编辑]注解

功能特性测试标准功能特性
__cpp_lib_saturation_arithmetic202311L(C++26)饱和算术

[编辑]可能的实现

参考 libstdc++ (GCC)

[编辑]示例

可以在 Compiler Explorer 上预览。

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

[编辑]参阅

(C++20)
重解释类型的对象表示为另一类型的对象表示
(函数模板)[编辑]
(C++17)
在一对边界值下夹逼一个值
(函数模板)[编辑]
(C++20)
检查整数是否在给定整数类型的范围内
(函数模板)[编辑]
close