命名空间
变体
操作

std::div_sat

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

计算饱和除法 x / y。如果 T 是有符号整数类型,xT 的最小值(最负值),并且 y == -1,则返回 T 的最大值;否则,返回 x / y

y 不得为 0,否则行为未定义。如果发生未定义行为,则函数调用不是核心常量表达式

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

目录

[编辑] 参数

x, y - 整数值

[编辑] 返回值

饱和的 x / y

[编辑] 注意

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

如果传递两个不同类型的参数,则调用将编译失败,即关于模板参数推导的行为与 std::minstd::max 相同。

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

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

[编辑] 可能的实现

namespace detail {
template<class T>
concept standard_or_extended_integral =
     std::is_integral_v<T> &&
    !std::is_same_v<std::remove_cv_t<T>, bool> &&
    !std::is_same_v<std::remove_cv_t<T>, char> &&
    !std::is_same_v<std::remove_cv_t<T>, char8_t> &&
    !std::is_same_v<std::remove_cv_t<T>, char16_t> &&
    !std::is_same_v<std::remove_cv_t<T>, char32_t> &&
    !std::is_same_v<std::remove_cv_t<T>, wchar_t>;
} // namespace detail
 
template<detail::standard_or_extended_integral T>
constexpr T div_sat( T x, T y ) noexcept
{
    if constexpr (std::is_signed_v<T>)
        if (x == std::numeric_limits<T>::min() && y == -1)
            return std::numeric_limits<T>::max();
    return x / y;
}

[编辑] 示例

可在 Compiler Explorer 上预览。

#include <climits>
#include <numeric>
 
static_assert
(""
    && (std::div_sat<int>(6, 3) == 2) // not saturated
    && (std::div_sat<int>(INT_MIN, -1) == INT_MAX) // saturated
    && (std::div_sat<unsigned>(6, 3) == 2) // not saturated
);
 
int main() {}

[编辑] 另请参阅

(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