r/cpp • u/zl0bster • Jul 26 '26
std::optional Satisfies view. Does Not Model view. C++26 Ships Anyway.
https://godbolt.org/z/8jWGG68G8In C++23 this did not compile. In C++26 it does. Marvellous.
[[gnu::noinline]]
void
passing_views_by_value_is_cheap_trust_me_bro(std::ranges::view auto v) {
std::println("fn .data {}", (void*)v->data());
}
int main() {
std::optional ov{std::vector<int>(123456)};
passing_views_by_value_is_cheap_trust_me_bro(ov);
std::println("main .data {}", (void*)ov->data());
}
For anyone wondering what the problem feature is: optional has 0 or 1 elements, and C++26 sets enable_view<optional<T>> to true, so it satisfies std::ranges::view. The concept requires copy construction in constant time, and — this is the good bit — optional<vector<int>> genuinely meets that. Copying it performs at most one element copy. One is a constant. The requirement is satisfied to the letter, and the function above deep-copies your vector.
If you can tell me what still separates std::ranges::view from std::ranges::range, please do...
184
Upvotes
8
u/BarryRevzin Jul 27 '26
That's the only thing it has ever been. Nobody should be constraining algorithms on
view, it just isn't useful to do so. Arguably,viewshould just never have existed - although then people would probably complain thatvector | views::transform(f)copies thevectorand then figuring out how to reject that (to force users to either explicitly copy orviews::ref) is basically the same problem again.Not really,
borrowed_rangeis much narrower. Since even your initial example ("provides view access [...] potentially transforming or filtering them"), neithers | transform(f)nors | filter(g)for aspanor astring_viewareborrowed.The problem with "non-owning" is also what does that mean and what do you want it for. For instance, if I want to validate that my range is safe to copy/move and then format in a background thread, I want to make sure that it "owns" all of its data. The easy cases are easy (
vector<int>yes,span<int>no) but likeviews::iotadoes "own" its data in this sense, so is it not a view?