CKTIS / C++
std::ranges::view_interface — an interface for custom views
std::ranges::view_interface is a CRTP base for custom views. It supplies convenience members from range operations, but their availability depends on the capabilities of the iterator and sentinel.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <ranges>
class D : public std::ranges::view_interface<D> {
public:
// Provide begin() and end().
};std::ranges::view_interface<D> uses CRTP: D publicly inherits from the specialization with its own type. You implement begin() and end(); the base derives convenience operations. Inheritance alone does not replace the requirements of std::ranges::view, including its semantic requirements. A view need not be non-owning.
Members are conditional: front() requires forward_range, back() additionally requires bidirectional_range and common_range, and operator[] requires random_access_range. size() requires forward_range and sized_sentinel_for; data() requires a contiguous iterator. empty() works for sized_range or forward_range. Explicit operator bool tests non-emptiness when ranges::empty is valid. The const overloads check the corresponding requirements for const D.
front() and back() require a non-empty range. operator[] does not check bounds; the index must designate an existing element. The example's int_view does not own its data: the array must remain alive during access through the view. A const view does not imply immutable elements, because its begin() returns int*.
This entry targets C++23. The supplied document is a rolling working draft and may include later additions, such as at(); do not treat it as a frozen C++23 specification. A repository compiler flag does not attest production-runtime behavior.
Examples
#include <iostream>
#include <ranges>
class int_view : public std::ranges::view_interface<int_view> {
int* first_;
int* last_;
public:
int_view(int* first, int* last) : first_(first), last_(last) {}
int* begin() const { return first_; }
int* end() const { return last_; }
};
static_assert(std::ranges::view<int_view>);
static_assert(std::ranges::contiguous_range<int_view>);
int main() {
int values[] = {10, 20, 30};
int_view v(values, values + 3);
std::cout << std::boolalpha << v.empty() << ' ' << v.size() << '\n';
std::cout << v.front() << ' ' << v.back() << ' ' << v[1] << '\n';
v.front() = 11;
std::cout << values[0] << '\n';
}
Result
false 3 10 30 20 11
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.