最終更新日時(UTC):
が更新

履歴 編集

function template
<numeric>

std::add_sat(C++26)

namespace std {
  template<class T>
    constexpr T add_sat(T x, T y) noexcept;
}

概要

飽和加算 x + y を計算する。

テンプレートパラメータ制約

Tは符号付き整数型または符号無し整数型であること。

戻り値

  • 無限の範囲で計算した値x + yが型Tで表現可能ならば、x + yを返す
  • そうでないとき、型Tで表現可能な最大値または最小値のうちx + yに近い方の値を返す

例外

投げない

#include <cstdint>
#include <numeric>
#include <print>

int main()
{
  // 1 + 2 = 3
  std::println("{}", std::add_sat(1, 2));

  // 200 + 200 = 400 -> 255(2**8-1)
  std::uint8_t x = 200;
  std::println("{}", std::add_sat(x, x));

  // -100 + -100 = -200 -> -128(-2**7)
  std::int8_t y = -100;
  std::println("{}", std::add_sat(y, y));
}

出力

3
255
-128

バージョン

言語

  • C++26

処理系

参照