< cpp‎ | ranges
Defined in header <ranges>
template<class D>

  requires std::is_class_v<D> && std::same_as<D, std::remove_cv_t<D>>

class view_interface : public view_base;
(since C++20)

std::ranges::view_interface is a helper class template for defining a view interface.

view_interface is typically used with CRTP:

class my_view : public std::ranges::view_interface<my_view> {
    auto begin() const { /*...*/ }
    auto end() const { /*...*/ }
    // empty() is provided if begin() returns a forward iterator
    // and end() returns a sentinel for it.

[edit] Member functions

Returns whether the deriving view is empty.
(public member function)
Returns whether the deriving view is not empty.
(public member function)
Get the address of deriving view's data. Provided if it satisfies contiguous_iterator
(public member function)
returns the number of elements. Provided only if the underlying (adapted) range satisfies sized_range
(public member function) [edit]
Return the first element in the deriving view.
(public member function)
Return the last element in the deriving view. Provided if it satisfies bidirectional_range and common_range
(public member function)
Return the nth element in the deriving view. Provided if it satisfies random_access_range
(public member function)

[edit] Example

#include <ranges>
#include <vector>
#include <iostream>
template <class T, class A>
class VectorView : public std::ranges::view_interface<VectorView<T, A>> {
    // We need to define a default constructor to satisfy the view concept.
    VectorView() = default;
    VectorView(const std::vector<T, A>& vec) :
        m_begin(vec.cbegin()), m_end(vec.cend()) {}
    auto begin() const { return m_begin; }
    auto end() const { return m_end; }
    typename std::vector<T, A>::const_iterator m_begin, m_end;
int main()
    std::vector<int> v = {1, 4, 9, 16};
    VectorView view_over_v{v};
    // We can iterate with begin() and end().
    for (int n : view_over_v) {
        std::cout << n << ' ';
    std::cout << '\n';
    // We get operator[] for free when inherting from view_interface
    // since we satisfy the random_access_range concept.
    for (std::ptrdiff_t i = 0; i < view_over_v.size(); i++) {
        std::cout << "v[" << i << "] = " << view_over_v[i] << '\n';


1 4 9 16 
v[0] = 1
v[1] = 4
v[2] = 9
v[3] = 16

[edit] See also

combines an iterator-sentinel pair into a view
(class template) [edit]