#ifndef MAMBA_INVOKE_HPP #define MAMBA_INVOKE_HPP #include #include "mamba/core/error_handling.hpp" namespace mamba { template auto safe_invoke(Func&& func, Args&&... args) -> tl::expected(func), std::forward(args)...)), mamba_error> { try { // If the callable is passed by being moved-in (r-value reference/temporary etc.) // we make sure that the lifetime of that callable doesnt go beyond this block. auto call = [&, callable = std::forward(func)] { return std::invoke(callable, std::forward(args)...); }; using Result = decltype(call()); if constexpr (std::is_void::value) { call(); return {}; } else { return call(); } } catch (const std::runtime_error& err) { return make_unexpected( std::string("callback invocation failed : ") + err.what(), mamba_error_code::unknown ); } catch (...) { return make_unexpected( "callback invocation failed : unknown error", mamba_error_code::unknown ); } } } #endif