-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathlatched.hpp
More file actions
61 lines (50 loc) · 1.54 KB
/
latched.hpp
File metadata and controls
61 lines (50 loc) · 1.54 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
#pragma once
#include <stdx/compiler.hpp>
#include <stdx/functional.hpp>
#include <stdx/type_traits.hpp>
#include <optional>
#include <type_traits>
#include <utility>
namespace stdx {
inline namespace v1 {
template <typename F> struct latched {
using value_type = stdx::remove_cvref_t<std::invoke_result_t<F>>;
constexpr explicit latched(F const &f) : lazy{f} {}
constexpr explicit latched(F &&f) : lazy{std::move(f)} {}
constexpr auto has_value() const noexcept -> bool {
return opt.has_value();
}
constexpr explicit operator bool() const noexcept {
return opt.has_value();
}
constexpr auto value() const & LIFETIMEBOUND -> value_type const & {
populate();
return *opt;
}
constexpr auto value() const && LIFETIMEBOUND -> value_type const && {
populate();
return *std::move(opt);
}
constexpr auto operator->() const LIFETIMEBOUND->value_type const * {
populate();
return opt.operator->();
}
constexpr auto operator*() const & LIFETIMEBOUND->decltype(auto) {
return value();
}
constexpr auto operator*() const && LIFETIMEBOUND->decltype(auto) {
return std::move(*this).value();
}
protected:
constexpr auto populate() const {
if (not opt.has_value()) {
opt.emplace(lazy);
}
}
with_result_of<F> lazy;
mutable std::optional<value_type> opt{};
};
template <typename C>
using latched_value_t = typename stdx::remove_cvref_t<C>::value_type;
} // namespace v1
} // namespace stdx