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:
#include <vector>
#include <ranges>
#include <cstdio>
#include "span.h"
static std::vector<int> g_vec{1, 2, 3, 4, 5, 6};
void span_view_filter() {
auto even = [](int i) { return 0 == i % 2; };
printf("evens: ");
for (int i : Span<int>(g_vec) | std::views::filter(even)) {
printf("%i ", i);
}
printf("\n");
}
void span_no_dangle()
{
auto get_span = [] {
return Span<int>(g_vec);
};
auto iter = std::ranges::max_element(get_span());
static_assert(std::is_same_v<int*, decltype(iter)>);
printf("max: %i\n", *iter);
}
int main()
{
span_no_dangle();
span_view_filter();
}
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 :)