Wednesday, May 8, 2024

First thoughts on std::expected

 std::expected -- what can you do with it?

There's  a fancy new thing in C++: std::expected. There's a lot of pots about it's awesomeness, but what is it, really?


Answer: if you've got a std::expected, you can do three important things. Let's give a name to our std::expected: it's called result. And as a reminder: std::expected holds one of two values, which in this post I'll cleverly call "first" or "second".

1. Just result by itself is  a bool. When first is set, it returns true; when second is set, false.

2. *result is just first.

3. result.error() returns second.

You can also chain them together, assuming you have code where you want to do a bunch of stuff in order and will never have to refactor the code to be multi-threaded, or handle error conditions weirdly, or log something and then fail, or a lot of things. Oh, and using functions means lots of global variables, and the function must return a std::expected, not an int.

1. result.and_then(function) will call function with *result. The function can take exactly one variable, and the function will only be called if result was set to first.

2. result.or_else(function) is like the opposite of and_then. It's also a function that takes a single parameter (love them globals!) but take in the type of second, not first, and is only called if the second was set (the 'unexpected' branch).

Want to make a std::expected?

If you need to return a std::expected, and you're setting the first value, just return it and it's automatically cast into an object as needed. If you need to return the second value (unexpected), return a std::unexpected(). Be sure to not new it; just return std::unexpected("second value").


And some useless crap

What if you you've got a std::expected where first is an int, but you really need a double? Can you cast it? Nope, you can't. Casting is now called "transform".

There's a tranform_error(), too.

First thoughts: what about exceptions?

Lord knows. I guess exceptions aren't a thing any more?

What happens if I need to set a breakpoint? Answer: good luck with that. 

The source code the std::expected iat about 1500 lines of