命名空间
变体
操作

std::ranges::constant_range

来自 cppreference.com
< cpp‎ | ranges
 
 
范围库
范围适配器
 
在头文件 <ranges> 中定义
template< class T >

concept constant_range =
    ranges::input_range<T> &&

    /*constant-iterator*/<ranges::iterator_t<T>>;
(1) (自 C++23 起)
辅助概念
template< class T >

concept /*constant-iterator*/ =
    std::input_iterator<T> &&

    std::same_as<std::iter_const_reference_t<T>, std::iter_reference_t<T>>;
(2) (仅供说明*)
1) constant_range 概念是对 range 的细化,其中 ranges::begin 返回一个 常量迭代器
2) 当输入迭代器的间接操作的结果是其常量引用类型时,概念 /*constant-iterator*/<T> 满足,这意味着只读。

[编辑] 示例

#include <ranges>
#include <span>
#include <string_view>
#include <vector>
 
// mechanisms for ensuring the parameter is a constant range
// 1) an overload set where the mutable one defers to the constant one
template<std::ranges::constant_range R>
void takes_any_range1(R&& r)
{
    // R is definitely a constant range
}
 
template<std::ranges::range R>
void takes_any_range1(R&& r)
{
    takes_any_range1(std::views::as_const(std::forward<R>(r)));
}
 
// 2) one function template that shadows its parameter
template<std::ranges::range R>
void takes_any_range2(R&& _r)
{
    auto r = std::views::as_const(std::forward<R>(_r));
 
    // r is definitely a constant range
    // never use _r again
}
 
// 3) one function template that recursively invokes itself
template<std::ranges::range R>
void takes_any_range3(R&& r)
{
    if constexpr (std::ranges::constant_range<R>)
    {
        // R is definitely a constant range
        // put implementation here
    }
    else
        takes_any_range3(std::views::as_const(std::forward<R>(r)));
}
 
static_assert
(
        std::ranges::constant_range<const std::vector<int>> and
    not std::ranges::constant_range<std::vector<int>> and
        std::ranges::constant_range<std::string_view> and
    not std::ranges::constant_range<std::span<int>> and
        std::ranges::constant_range<std::span<const int>> and
    not std::ranges::constant_range<const std::span<int>>
);
 
int main() {}