chromium / subspace

A concept-centered standard library for C++20, enabling safer and more reliable products and a more modern feel for C++ code.; Also home of Subdoc the code-documentation generator.
https://suslib.cc
Apache License 2.0
89 stars 15 forks source link

Add a TRY macro for early-out on types that satisfy `Try` and report failure (Option, Result, optional, expected..) #299

Open danakj opened 1 year ago

danakj commented 1 year ago

Chromium is gaining RETURN_IF_ERROR(e) which is built around base::expected (like std::expected).

STX has TRY_OK and TRY_SOME which are similar and hard coded to its Result and Option types.

Subspace has a sus::ops::Try concept which is used to early terminate operations like try_fold. The concept is satisfied by sus::result::Result and sus::Option. It can be extended to make std::optional and std::expected satisfy sus::ops::Try as well, in the same way that std::vector now satisfies sus::iter::FromIterator.

Providing a TRY() macro that will early out when the Try object reports failure would allow this mechanism to be applied across many different types.

If needed we can add additional hooks into the requirements of the Try concept to provide good error messages.

danakj commented 1 year ago

I'm adding Error and its type-erased Box<DynError> and that means a function returning Result<T, Box<DynError>> can return any Error if it spells it sus::err(sus::into(SomeErrorType())) so the TRY macro should also do the into step.