std::add_sat
来自 cppreference.cn
定义于头文件 <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); // 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++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 |