- numeric[meta header]
- function template[meta id-type]
- std[meta namespace]
- cpp26[meta cpp]
namespace std {
template<class T>
constexpr T saturating_sub(T x, T y) noexcept;
}飽和減算 x - y を計算する。
Tは符号付き整数型または符号無し整数型であること。
- 無限の範囲で計算した値
x - yが型Tで表現可能ならば、x - yを返す - そうでないとき、型
Tで表現可能な最大値または最小値のうちx - yに近い方の値を返す
投げない
#include <cstdint>
#include <numeric>
#include <print>
int main()
{
// 3 - 1 = 2
std::println("{}", std::saturating_sub(3, 1));
// 1 - 3 = -2 -> 0
std::println("{}", std::saturating_sub(1u, 3u));
// -100 - 50 = -150 -> -128(-2**7)
std::int8_t x = -100, y = 50;
std::println("{}", std::saturating_sub(x, y));
}- std::saturating_sub[color ff0000]
2
0
-128
- C++26
- Clang: ??
- GCC: ??
- ICC: ??
- Visual C++: ??
- P0543R3 Saturation arithmetic
- LWG Issue 4030. Clarify whether arithmetic expressions in [numeric.sat.func] are mathematical or C++
- C++26で、飽和演算関数の算術演算が無限精度の数学的演算として行われることが明確化された(cpprefjpでは既に「無限の範囲で計算した値」と記述している)
- P4052R0 Renaming saturation arithmetic functions