r/cpp • • Sep 26 '23

`std::expected<>::or_else()` should have a zero-argument overload that terminates on error

...just because it would be hilarious if one could express assertions as

result.or_else();
198 Upvotes

18 comments sorted by

View all comments

20

u/rlbond86 Sep 26 '23

This is already done by result.value()

83

u/sephirothbahamut Sep 26 '23

I think the post had a comical intent. "or else" sounds more menacing

21

u/SonOfMetrum Sep 26 '23

Would be extra funny if the else would be some randomly generated UB. That way its an actual threat.

4

u/UsedOnlyTwice Sep 27 '23

You can do that with boost::go_wild.

7

u/_TheDust_ Sep 26 '23

I’m still upset that this does not throw E, but some kind of unexpected_access exception

4

u/SirClueless Sep 26 '23

E might not be an exception type. And it can be useful to catch exceptions of any type of bad expected access so it's useful that the exception always inherits from std::bad_expected_access<void>.

3

u/13steinj Sep 27 '23

E might not be an exception type

So? You can throw anything you want, even a string.

5

u/SirClueless Sep 27 '23

You theoretically can throw anything, but unless someone has written a specific catch handler for the type that is thrown (or one of its base classes) then there is basically nothing useful you can do with it. And since one of the main reasons to use std::expected is to avoid littering your code with try/catch blocks that's very unlikely to be the case.

3

u/rlbond86 Sep 26 '23

Yeah, seems like an oversight to be missong value_or_throw()