From cppreference.com
template<classD>requiresstd::is_class_v<D>&&std::same_as<D,std::remove_cv_t<D>>classview_interface;(since C++20)std::ranges::view_interface is a helper class template for defining a view interface.
view_interface is typically used with
:
classmy_view:publicstd::ranges::view_interface<my_view>{public:autobegin()const{/*...*/}autoend()const{/*...*/}// empty() is provided if begin() returns a forward iterator// and end() returns a sentinel for it.};Member functions
returns whether the derived view is empty, provided only if it satisfies
or
(public member function)
(C++23)
returns a constant iterator to the beginning of the range
(public member function)
(C++23)
returns a sentinel for the constant iterator of the range
(public member function)
returns whether the derived view is not empty, provided only if
is applicable to it
(public member function)
gets the address of derived view's data, provided only if its iterator type satisfies
(public member function)
returns the number of elements in the derived view. Provided if it satisfies
and its sentinel and iterator type satisfy
.
(public member function)
returns the first element in the derived view, provided if it satisfies
(public member function)
returns the last element in the derived view, provided only if it satisfies
and
(public member function)
returns the nth element in the derived view, provided only if it satisfies
(public member function)
Example
Run this code
#include<iostream>#include<ranges>#include<vector>template<classT,classA>classVectorView:publicstd::ranges::view_interface<VectorView<T,A>>{public:VectorView()=default;VectorView(conststd::vector<T,A>&vec):m_begin(vec.cbegin()),m_end(vec.cend()){}autobegin()const{returnm_begin;}autoend()const{returnm_end;}private:typenamestd::vector<T,A>::const_iteratorm_begin{},m_end{};};intmain(){std::vector<int>v={1,4,9,16};VectorViewview_over_v{v};// We can iterate with begin() and end().for(intn:view_over_v)std::cout<<n<<' ';std::cout<<'\n';// We get operator[] for free when inheriting from view_interface// since we satisfy the random_access_range concept.for(std::ptrdiff_ti=0;i!=view_over_v.size();++i)std::cout<<"v["<<i<<"] = "<<view_over_v[i]<<'\n';}Output:
1 4 9 16 v[0] = 1 v[1] = 4 v[2] = 9 v[3] = 16 Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++20 view_interface was required to be derived from view_base,
which sometimes required multiple view_base subobjects in a view inheritance removed See also