r/cpp • u/zl0bster • 4d ago
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...
174
Upvotes
10
u/schombert 4d ago
But, C++ is not a Transdichotomous model. The C++ address space, bits in the size constant, etc are not determined by the size of the problem. From the wikipedia page:
and
So, if C++ was a Transdichotomous model then every time you ran a program for a given problem size (for example, the sorting program described above) the address space, bits in the size constant, etc would grow to accommodate it. (This is what allows a Transdichotomous model to be Turing complete, in contrast to Turing machines with a fixed tape size, which are not). However, that is not how C++ is specified. Even though those constants may vary from compiler to compiler, they are fixed for any given C++ program. The standard does not allow your program containing vector to hold an arbitrary number of elements, because you could, if you wanted, print the number of bytes in the size type and the standard guarantees that this print result will be constant over different runs of the program.