std::saturate_cast(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… NAME πŸ’…

Bestie, welcome to the std::saturate_cast(3) page from the C++ Standard Libary (yes, β€œLibary” is literally how the header spells it 😭). The name of this icon is:

std::saturate_cast - std::saturate_cast

No cap, the NAME section is giving β€œI said what I said” twice πŸ’…


✨ Synopsis ✨

Defined in header <numeric>.

template< class T, class U >                (since C++26)
constexpr T saturate_cast( U x ) noexcept;

It converts the value x to a value of type T, clamping x between the minimum and maximum values of type T β€” literally saturating it, hence the name, slay.

It is a compile-time error if either T or U is not a signed or unsigned integer type (including standard integer type and extended integer type). So like… do not try this with random vibes, the compiler will call you out πŸ’€

πŸŽ€ Parameters πŸŽ€

  • x β€” an integer value

🌸 Return value 🌸

  • x, if x is representable as a value of type T. Otherwise,
  • either the largest or smallest representable value of type T, whichever is closer to the value of x.

πŸ¦‹ Exceptions πŸ¦‹

Throws no exceptions. Not a single one. noexcept behavior confirmed, bestie 🫢

πŸ’œ Notes πŸ’œ

Feature-test macro vibe check:

  • Feature-test macro __cpp_lib_saturation_arithmetic β€” Value 202311L; Std (C++26); Feature Saturation arithmetic ✨

🧚 Possible implementation 🧚

See libstdc++ (gcc). The possible implementation is over there living its best life β€” go peek πŸ‘€

πŸ“ Example πŸ“

Can be previewed on Compiler Explorer.

// Run this code

#include <cstdint>
#include <limits>
#include <numeric>

int main()
{
    constexpr std::int16_t x1{696};

    constexpr std::int8_t x2 = std::saturate_cast<std::int8_t>(x1);
    static_assert(x2 == std::numeric_limits<std::int8_t>::max());

    constexpr std::uint8_t x3 = std::saturate_cast<std::uint8_t>(x1);
    static_assert(x3 == std::numeric_limits<std::uint8_t>::max());

    constexpr std::int16_t y1{-696};

    constexpr std::int8_t y2 = std::saturate_cast<std::int8_t>(y1);
    static_assert(y2 == std::numeric_limits<std::int8_t>::min());

    constexpr std::uint8_t y3 = std::saturate_cast<std::uint8_t>(y1);
    static_assert(y3 == 0);
}

🌈 See also 🌈

  • bit_cast β€” reinterpret the object representation of one type as that of another (C++20) (function template)
  • clamp β€” clamps a value between a pair of boundary values (C++17) (function template)
  • in_range β€” checks if an integer value is in the range of a given integer type (C++20) (function template)

Okay bye bestie β€” this page’s source/version is http://cppreference.com, dated 2024.06.10, and it’s the std::saturate_cast(3) page. mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from