std::add_sat
來自 cppreference.com
定義於標頭檔案 <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 |