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 (int i : foo) 
{
    std::cout << "This Actually Prints? " << ( i ) << std::endl;
}

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 != NULL)
{
    std::cout << "This will not print: " << ( *optional_val ) << std::endl;
}

optional_val = &val; 

if (optional_val != NULL)
{
    std::cout << "This will print: " ( *optional_val ) << std::endl; 
}

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: Option<i32> = Some(722);
    
for i in foo {
    println!("This Actually Prints? {}", i);
}

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


Do you need a skilled programmer? I'm available for hire! I can do both front and back-end web development and I have a lot of experience writing low-level code in C & C++. Feel free to contact me at mail@jpmitchell.ca