命名空间
变体
操作

std::add_sat

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

计算饱和加法 x + y。此运算(与内置的整数算术运算不同)的行为如同它是一个具有无限范围的数学运算。设 q 表示此运算的结果。 返回

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

此重载仅在 T整数类型时参与重载决议,即:signed charshortintlonglong long、扩展的有符号整数类型或此类类型的无符号版本。 特别是,T 不得是(可能带有 cv 限定符的)boolcharwchar_tchar8_tchar16_tchar32_t,因为这些类型不用于算术运算。

目录

[编辑] 参数

x, y - 整数值

[编辑] 返回值

饱和的 x + y

[编辑] 注解

与内置的整数算术运算符不同,整型提升不适用于 xy 参数。

如果传递了两种不同类型的参数,则调用将无法编译,即,相对于模板参数推导的行为与 std::minstd::max 相同。

大多数现代硬件架构都有效支持 SIMD 向量的饱和算术,包括 x86 的 SSE2 和 ARM 的 NEON。

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

[编辑] 可能的实现

参见 libstdc++ (gcc)

[编辑] 示例

可以在 Compiler Explorer 上预览。

#include <climits>
#include <limits>
#include <numeric>
 
static_assert(CHAR_BIT == 8);
static_assert(UCHAR_MAX == 255);
 
int main()
{
    constexpr int a = std::add_sat(3, 4); // no saturation occurs, T = int
    static_assert(a == 7);
 
    constexpr unsigned char b = std::add_sat<unsigned char>(UCHAR_MAX, 4); // saturated
    static_assert(b == UCHAR_MAX);
 
    constexpr unsigned char c = std::add_sat(UCHAR_MAX, 4); // not saturated, T = int
        // add_sat(int, int) returns int tmp == 259,
        // then assignment truncates 259 % 256 == 3
    static_assert(c == 3);
 
//  unsigned char d = std::add_sat(252, c); // Error: inconsistent deductions for T
 
    constexpr unsigned char e = std::add_sat<unsigned char>(251, a); // saturated
    static_assert(e == UCHAR_MAX);
        // 251 is of type T = unsigned char, `a` is converted to unsigned char value;
        // might yield an int -> unsigned char conversion warning for `a`
 
    constexpr signed char f = std::add_sat<signed char>(-123, -3); // not saturated
    static_assert(f == -126);
 
    constexpr signed char g = std::add_sat<signed char>(-123, -13); // saturated
    static_assert(g == std::numeric_limits<signed char>::min()); // g == -128
}

[编辑] 参见

(C++26)
两个整数的饱和减法运算
(函数模板) [编辑]
(C++26)
两个整数的饱和乘法运算
(函数模板) [编辑]
(C++26)
两个整数的饱和除法运算
(函数模板) [编辑]
返回一个钳制到另一个整数类型范围的整数值
(函数模板) [编辑]
(C++17)
将值钳制在一对边界值之间
(函数模板) [编辑]
(C++20)
检查整数值是否在给定整数类型的范围内
(函数模板) [编辑]
[静态]
返回给定非浮点类型的最小有限值,或给定浮点类型的最小正规正值
(std::numeric_limits<T> 的公共静态成员函数) [编辑]
[静态]
返回给定类型的最大有限值
(std::numeric_limits<T> 的公共静态成员函数) [编辑]

[编辑] 外部链接

1.  饱和算术的无分支实现 — Locklessinc.com, 2012
2.  C++ Weekly - Ep 459 - C++26 的饱和数学运算 — Youtube.com, 2024-12-16