This is a c++20 feature, so it’s obviously not a rush to get in, but it may be useful while we play around with ranges in the codebase before actually switching to c++20.
This matches the behavior of std::span.
The below sample program demonstrates what these enable:
0#include <vector>
1#include <ranges>
2#include <cstdio>
3#include "span.h"
4
5static std::vector<int> g_vec{1, 2, 3, 4, 5, 6};
6
7void span_view_filter() {
8 auto even = [](int i) { return 0 == i % 2; };
9 printf("evens: ");
10 for (int i : Span<int>(g_vec) | std::views::filter(even)) {
11 printf("%i ", i);
12 }
13 printf("\n");
14}
15
16void span_no_dangle()
17{
18 auto get_span = [] {
19 return Span<int>(g_vec);
20 };
21 auto iter = std::ranges::max_element(get_span());
22 static_assert(std::is_same_v<int*, decltype(iter)>);
23 printf("max: %i\n", *iter);
24}
25
26int main()
27{
28 span_no_dangle();
29 span_view_filter();
30}
Compiled with: g++-10 -O2 -std=c++2a span.cpp -o span
If enable_view
is disabled, the first example will fail to compile.
If enable_borrowed_range
is disabled, the second will fail to compile.
Sidenote: std::ranges::dangling
is neat :)