-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncResult.hpp
More file actions
69 lines (54 loc) · 1.66 KB
/
AsyncResult.hpp
File metadata and controls
69 lines (54 loc) · 1.66 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#ifndef _LIBRARY_UTILITIES_ASYNCRESULT_HPP
#define _LIBRARY_UTILITIES_ASYNCRESULT_HPP
#include <concepts>
#include <future>
#include <type_traits>
#include <utility>
namespace Utilities
{
template<typename ResultT>
requires(std::copyable<ResultT> || std::movable<ResultT>)
class AsyncResult
{
std::future<ResultT> m_waitable;
public:
explicit AsyncResult(std::future<ResultT>&& waitable)
: m_waitable(std::move(waitable))
{
}
AsyncResult() = default;
~AsyncResult() = default;
AsyncResult(const AsyncResult&) = delete;
AsyncResult& operator=(const AsyncResult&) = delete;
AsyncResult(AsyncResult&&) = default;
AsyncResult& operator=(AsyncResult&&) = default;
template<typename Fn, std::enable_if_t<!std::is_same_v<void, ResultT>, int> = 0>
requires std::movable<Fn>
inline auto then(Fn&& callback)
{
using return_t = std::invoke_result_t<Fn, ResultT>;
std::promise<return_t> prms;
prms.set_value(std::move(callback(m_waitable.get())));
return AsyncResult<return_t>{std::move(prms.get_future())};
}
ResultT get()
{
if constexpr (std::is_same_v<void, ResultT>)
{
m_waitable.get();
return;
}
return m_waitable.get();
}
void wait()
{
m_waitable.wait();
return;
}
bool valid() const
{
return m_waitable.valid();
}
};
} // namespace Utilities
#endif // !_LIBRARY_UTILITIES_ASYNCRESULT_HPP