-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTryAsync.mpp
More file actions
28 lines (26 loc) · 916 Bytes
/
TryAsync.mpp
File metadata and controls
28 lines (26 loc) · 916 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
export module CppUtils.Thread.TryAsync;
import std;
export namespace CppUtils::Thread
{
[[nodiscard]] inline auto tryAsync(auto&& function, auto&&... args) -> decltype(auto)
{
return std::async(std::launch::async, [function = std::forward<decltype(function)>(function), ... args = std::forward<decltype(args)>(args)]() mutable -> std::expected<std::invoke_result_t<decltype(function), decltype(args)...>, std::runtime_error> {
try
{
if constexpr (std::is_void_v<std::invoke_result_t<decltype(function), decltype(args)...>>)
function(std::forward<decltype(args)>(args)...);
else
return function(std::forward<decltype(args)>(args)...);
}
catch (const std::exception& exception)
{
return std::unexpected{std::runtime_error{exception.what()}};
}
catch (...)
{
return std::unexpected{std::runtime_error{"Unknown exception occurred"}};
}
return {};
});
}
}