Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::saturate_cast

      From cppreference.com
      <cpp‎ |numeric
       
       
       
      Saturation arithmetic
      Functions
      (C++26)
      (C++26)
      (C++26)
      (C++26)
      saturate_cast
      (C++26)
       
      Defined in header<numeric>
      template<class T,class U>
      constexpr T saturate_cast( U x)noexcept;
      (since C++26)

      Converts the valuex to a value of typeT, clampingx between the minimum and maximum values of typeT.

      The program is ill-formed if eitherT orU is not a signed or unsignedinteger type (includingstandard integer type andextended integer type).

      Contents

      [edit]Parameters

      x - an integer value

      [edit]Return value

      • x, ifx is representable as a value of typeT. Otherwise,
      • either the largest or smallest representable value of typeT, whichever is closer to the value ofx.

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_saturation_arithmetic202311L(C++26)Saturation arithmetic

      [edit]Possible implementation

      Seelibstdc++ (GCC).

      [edit]Example

      Can be previewed onCompiler Explorer.

      Run this code
      #include <cstdint>#include <limits>#include <numeric> int main(){constexprstd::int16_t x1{696}; constexprstd::int8_t x2= std::saturate_cast<std::int8_t>(x1);    static_assert(x2==std::numeric_limits<std::int8_t>::max()); constexprstd::uint8_t x3= std::saturate_cast<std::uint8_t>(x1);    static_assert(x3==std::numeric_limits<std::uint8_t>::max()); constexprstd::int16_t y1{-696}; constexprstd::int8_t y2= std::saturate_cast<std::int8_t>(y1);    static_assert(y2==std::numeric_limits<std::int8_t>::min()); constexprstd::uint8_t y3= std::saturate_cast<std::uint8_t>(y1);    static_assert(y3==0);}

      [edit]See also

      (C++20)
      reinterpret the object representation of one type as that of another
      (function template)[edit]
      (C++17)
      clamps a value between a pair of boundary values
      (function template)[edit]
      (C++20)
      checks if an integer value is in the range of a given integer type
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/numeric/saturate_cast&oldid=181994"

      [8]ページ先頭

      ©2009-2025 Movatter.jp