Namespaces
Variants
Views
Actions

std::in_range

From cppreference.com
< cpp‎ | utility
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
in_range
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
Defined in header <utility>
template< class R, class T >
constexpr bool in_range( T t ) noexcept;
(since C++20)

Returns true if the value of t is in the range of values that can be represented in R, that is, if t can be converted to R without data loss.

It is a compile-time error if either T or R is not a signed or unsigned integer type (including standard integer type and extended integer type).

Contents

[edit] Parameters

t - value to test

[edit] Return value

true if the value of t is representable in R, false otherwise.

[edit] Possible implementation

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());
}

[edit] Notes

This function cannot be used with std::byte, char, char8_t, char16_t, char32_t, wchar_t and bool.

[edit] Example

#include <utility>
#include <iostream>
#include <iomanip>
 
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';
}

Output:

false
true