zeus

Unnamed repository; edit this file 'description' to name the repository.
git clone Unknown
Log | Files | Refs

commit c63b26e6334cfaab952e88af5234077be1bf0790
parent 10dce9768bcab497d517e82b8e6e487440339549
author Dimitrije Dobrota < mail@dimitrijedobrota.com >
date Mon, 9 Jun 2025 16:02:19 +0200

Throwing_type shorthand

Diffstat:
A throwing_try.cpp | +++++++++++++++++++++++++++++++++++++++++++

1 files changed, 43 insertions(+), 0 deletions(-)


diff --git a/ throwing_try.cpp b/ throwing_try.cpp

@@ -0,0 +1,43 @@

/*
* Proof of concept C++23 exception interface shorthand
*/

#include <functional>
#include <expected>
#include <string>


template <class Val, class Err, class... Args, class... CallArgs>
Val throwing_try(std::expected<Val, Err>(*func)(Args...), CallArgs&&... callargs) {
return std::invoke(func, std::forward<CallArgs>(callargs)...)
.or_else([](const auto& err) -> std::expected<Val, Err> {
throw err;
}).value();
}

template <class Val, class Err, class Type, class... Args, class... CallArgs>
Val throwing_try(std::expected<Val, Err>(Type::* func)(Args...), Type* self, CallArgs&&... callargs) {
return std::invoke(func, self, std::forward<CallArgs>(callargs)...)
.or_else([](const auto& err) -> std::expected<Val, Err> {
throw err;
}).value();
}

struct test {
std::expected<int, std::string> try_op(int x) {
if (x > 0) {
return x;
}
return std::unexpected{"op: value must be positive"};
}

auto op(int x) {
return throwing_try(&test::try_op, this, x);
}
};

int main() {
// return throwing_wrapper(op)(3);
test t;
return t.op(-54);
}`