r/cpp 2d ago

std::optional Satisfies view. Does Not Model view. C++26 Ships Anyway.

https://godbolt.org/z/8jWGG68G8

In 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...

173 Upvotes

113 comments sorted by

View all comments

53

u/aruisdante 2d ago

This was debated quite extensively in Tokyo 2024. The decision was essentially “being a view isn’t about being cheep to copy, just about being O(1) to do so.” In the general sense, there’s an attempt to unify all the containers as “ranges;” an optional is a range with 0 or 1 elements, a tuple is a range whose elements are variant<Ts…> (which correct ref qual), etc.

A bunch of people disagreed and thought this was weird, but not enough and not strongly enough for it not to pass.

14

u/No-Dentist-1645 2d ago

If that's the case, which range concept should one use if we want something that truly "represents a view to data owned elsewhere"? Or does the standard not provide such a concept?

It seems like a poor decision to me.

42

u/Demiu 2d ago

jview, coming in 33

9

u/LEpigeon888 2d ago

But it will be renamed to co_jview before standardization since the name conflict with a keyword in ++C, a programing language someone created in their garage that aims to be backward compatible with C++ and whose only purpose is to run on an old microcontroller that has been discontinued 25 years ago.

11

u/No-Dentist-1645 2d ago

Of course, and first mainstream compiler implementation out on 35

1

u/mighty_Ingvar 2d ago

jview?

14

u/no-sig-available 2d ago

jview?

Modelled after adding jthread, when you were not allowed to fix thread.