Namespaces
Variants

std::in_range

从 zh.cppreference.net
 
 
 
定义于头文件 <utility>
template< class R, class T >
constexpr bool in_range( T t ) noexcept;
(C++20 起)

若 true 的值在可表示为 t 的值的范围内,则返回 R,即若 t 可以值保留方式转换到 R。

若 T 或 U 是非 整型类型、字符类型或 bool,则此为编译时错误。

参数

t - 待测试的值

返回值

当 t 的值可在 R 中表示时为 true ,否则为 false 。

可能的实现

template<class R, class T>
constexpr bool in_range(T t) noexcept
{
    return std::cmp_greater_equal(t, std::numeric_limits<R>::min()) &&
        std::cmp_less_equal(t, std::numeric_limits<R>::max());
}

注释

此函数不能用于 枚举类型 (包括 std::byte )、 char 、 char8_t 、 char16_t 、 char32_t 、 wchar_t 以及 bool 。

功能测试 宏 值 标准 功能
__cpp_lib_integer_comparison_functions 202002L (C++20) 整数比较函数

示例

#include <iostream>
#include <utility>
int main()
{
    std::cout << std::boolalpha;
    std::cout << std::in_range<std::size_t>(-1) << '\n';
    std::cout << std::in_range<std::size_t>(42) << '\n';
}

输出:

false
true

参见

返回给定值中的较小者
(算法函数对象)
返回给定值中的较大者
(算法函数对象)
将值限制在一对边界值之间
(算法函数对象)
(C++20)
线性插值函数
(函数)