Namespaces
Variants

std:: in_range

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

t 的值处于 R 可表示的数值范围内时返回 true ,即当 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)
线性插值函数
(函数)