userver: userver/utils/invoke_with_expected.hpp Source File
Loading...
Searching...
No Matches
invoke_with_expected.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/invoke_with_expected.hpp
4/// @brief @copybrief utils::InvokeWithExpected
5
6#include <concepts>
7#include <exception>
8#include <functional>
9#include <type_traits>
10#include <utility>
11
12#include <userver/utils/expected.hpp>
13
14USERVER_NAMESPACE_BEGIN
15
16namespace utils {
17
18/// @brief Invoke a callable and return its result or exception in @ref utils::expected.
19///
20/// @param func Callable invoked once, preserving its value category.
21/// @returns The decayed result, or a `std::exception_ptr` preserving the dynamic type
22/// of a caught `std::exception`-derived exception. Supports void and move-only results.
23/// Reference results are copied into the returned value; array and function references
24/// decay to pointers and do not extend the lifetime of their referents.
25/// @throws Non-`std::exception`-derived exceptions propagate; they are never stored.
26template <std::invocable Func>
27auto InvokeWithExpected(Func&& func) -> expected<std::decay_t<std::invoke_result_t<Func>>, std::exception_ptr> {
28 try {
29 if constexpr (std::is_void_v<std::invoke_result_t<Func>>) {
30 std::invoke(std::forward<Func>(func));
31 return {};
32 } else {
33 return std::invoke(std::forward<Func>(func));
34 }
35 } catch (const std::exception&) {
36 return unexpected(std::current_exception());
37 }
38}
39
40} // namespace utils
41
42USERVER_NAMESPACE_END