zeusUnnamed repository; edit this file 'description' to name the repository. |
git clone Unknown |
Log | Files | Refs |
throwing_try.cpp (1180B)
0 /*
1 * Proof of concept C++23 exception interface shorthand
2 */
4 #include <functional>
5 #include <expected>
6 #include <string>
9 template <class Val, class Err, class... Args, class... CallArgs>
10 Val throwing_try(std::expected<Val, Err>(*func)(Args...), CallArgs&&... callargs) {
11 return std::invoke(func, std::forward<CallArgs>(callargs)...)
12 .or_else([](const auto& err) -> std::expected<Val, Err> {
13 throw err;
14 }).value();
15 }
17 template <class Val, class Err, class Type, class... Args, class... CallArgs>
18 Val throwing_try(std::expected<Val, Err>(Type::* func)(Args...), Type* self, CallArgs&&... callargs) {
19 return std::invoke(func, self, std::forward<CallArgs>(callargs)...)
20 .or_else([](const auto& err) -> std::expected<Val, Err> {
21 throw err;
22 }).value();
23 }
25 struct test {
26 std::expected<int, std::string> try_op(int x) {
27 if (x > 0) {
28 return x;
29 }
30 return std::unexpected{"op: value must be positive"};
31 }
33 auto op(int x) {
34 return throwing_try(&test::try_op, this, x);
35 }
36 };
38 int main() {
39 // return throwing_wrapper(op)(3);
40 test t;
41 return t.op(-54);
42 }`