For C++26, a proposal was made to add range support to std::optional. That means source code that looks like this will become valid syntax.
std::optional<int> foo = 722;
for
This looks very strange, but it can make a lot of sense if you shift your prespective on what std::optional actually is.
The most intuitive way to look at std::optional is to see it as a nullable type or even just a pointer with an extra layer of memory safety. Equivalent to this c-style code.
int val = 722;
int* optional_val = NULL;
if
optional_val = &val;
if
But what if you thought of std::optional as being a range? For me this is what made it click in my mind.
A range of values that has only 0 or 1 elements.
'Nullability' fits neatly into the idea of 'iterability' since aquiring a nullable value is so often followed by a scoped block of code that acts against the nullable's true value (if it exists). This is very similar to what a loop does with an iterator value.
The idea to treat a nullable as an iterable is not new. Many other languages already have this idiom. For example, here's some Rust code that demonstrates it.
let foo: = Some;
for i in foo
I like the idea. Code written in this way has an 'elegance' that is very satisfying to write. I've been using this in my own code for a while now.
If you want to know more, you can see the proposal for C++26 here