Namespaces
Variants

std:: add_sat

From cppreference.net
Saturation arithmetic
Functions
add_sat
(C++26)
(C++26)
(C++26)
(C++26)
定义于头文件 <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 char short int long long long 、扩展有符号整数类型或其对应的无符号版本。特别地, T 不得为(可能带有 cv 限定符的) bool char wchar_t char8_t char16_t char32_t ,因为这些类型不用于算术运算。

目录

参数

x, y - 整数值

返回值

饱和的 x + y

注释

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

如果传入两个不同类型的参数,该调用将无法通过编译,即相对于 模板实参推导 的行为与 std::min std::max 相同。

大多数现代硬件架构都对 SIMD向量 的饱和算术运算提供高效支持,包括面向 x86 架构的 SSE2 以及面向 ARM 架构的 NEON

功能测试 标准 功能
__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); // 未发生饱和处理,T = int
    static_assert(a == 7);
    constexpr unsigned char b = std::add_sat<unsigned char>(UCHAR_MAX, 4); // 已饱和
    static_assert(b == UCHAR_MAX);
    constexpr unsigned char c = std::add_sat(UCHAR_MAX, 4); // 未饱和处理,T = int
        // add_sat(int, int) 返回 int 类型临时值 tmp == 259,
        // 随后赋值时发生截断 259 % 256 == 3
    static_assert(c == 3);
//  unsigned char d = std::add_sat(252, c); // 错误:对 T 的类型推导不一致
    constexpr unsigned char e = std::add_sat<unsigned char>(251, a); // 已饱和
    static_assert(e == UCHAR_MAX);
        // 251 属于 T = unsigned char 类型,`a` 被转换为 unsigned char 值;
        // 可能因 `a` 的 int -> unsigned char 转换产生警告
    constexpr signed char f = std::add_sat<signed char>(-123, -3); // 未饱和
    static_assert(f == -126);
    constexpr signed char g = std::add_sat<signed char>(-123, -13); // 已饱和
    static_assert(g == std::numeric_limits<signed char>::min()); // g == -128
}

参见

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

外部链接

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