std::saturate_cast
來自 cppreference.com
定義於標頭檔案 <numeric> |
||
template< class T, class U > constexpr T saturate_cast( U x ) noexcept; |
(C++26 起) | |
將值 x 轉換為 T
型別的值,將 x 限制在 T
型別的最小值和最大值之間。
如果 T
或 U
不是有符號或無符號整數型別(包括標準整數型別和擴充套件整數型別),則程式格式錯誤。
目錄 |
[編輯] 引數
x | - | 一個整數值 |
[編輯] 返回值
- 如果 x 可以表示為
T
型別的值,則返回 x。否則, - 返回
T
型別中最大或最小可表示的值,以更接近 x 的值為準。
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_saturation_arithmetic |
202311L |
(C++26) | 飽和算術 |
[編輯] 可能實現的示例
參見 libstdc++ (GCC)。
[編輯] 示例
可在 Compiler Explorer 上預覽。
執行此程式碼
#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); }
[編輯] 參見
(C++20) |
將一種型別的物件表示重新解釋為另一種型別的物件表示 (函式模板) |
(C++17) |
將值限制在邊界值對之間 (函式模板) |
(C++20) |
檢查整數值是否在給定整數型別的範圍內 (函式模板) |