Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 1 | #pragma once |
2 | |||||
3 | #include <optional> | ||||
4 | #include <utility> | ||||
5 | |||||
6 | namespace utils | ||||
7 | { | ||||
8 | |||||
9 | template <class F> | ||||
10 | struct Ensure | ||||
11 | { | ||||
12 | Ensure() = default; | ||||
13 | |||||
14 | template <class U> | ||||
15 | Ensure(U&& functor) : functor(std::forward<U>(functor)) | ||||
16 | {} | ||||
17 | |||||
Patrick Williams | 3a1c297 | 2023-05-10 07:51:04 -0500 | [diff] [blame] | 18 | Ensure(F functor) : functor(std::move(functor)) {} |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 19 | |
Szymon Dompke | bcf045a | 2022-09-16 15:23:30 +0200 | [diff] [blame] | 20 | Ensure(Ensure&& other) = delete; |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 21 | Ensure(const Ensure&) = delete; |
22 | |||||
23 | ~Ensure() | ||||
24 | { | ||||
Michal Orzel | 6050b65 | 2024-12-20 11:43:06 +0100 | [diff] [blame] | 25 | call(); |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 26 | } |
27 | |||||
28 | template <class U> | ||||
29 | Ensure& operator=(U&& other) | ||||
30 | { | ||||
Michal Orzel | 6050b65 | 2024-12-20 11:43:06 +0100 | [diff] [blame] | 31 | call(); |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 32 | functor = std::move(other); |
33 | return *this; | ||||
34 | } | ||||
35 | |||||
Szymon Dompke | bcf045a | 2022-09-16 15:23:30 +0200 | [diff] [blame] | 36 | Ensure& operator=(Ensure&& other) = delete; |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 37 | |
38 | Ensure& operator=(std::nullptr_t) | ||||
39 | { | ||||
Michal Orzel | 6050b65 | 2024-12-20 11:43:06 +0100 | [diff] [blame] | 40 | call(); |
41 | functor = std::nullopt; | ||||
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 42 | return *this; |
43 | } | ||||
44 | |||||
45 | Ensure& operator=(const Ensure&) = delete; | ||||
46 | |||||
Krzysztof Grobelny | 973b4bb | 2022-04-25 17:07:27 +0200 | [diff] [blame] | 47 | explicit operator bool() const |
48 | { | ||||
49 | return static_cast<bool>(functor); | ||||
50 | } | ||||
51 | |||||
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 52 | private: |
Michal Orzel | 6050b65 | 2024-12-20 11:43:06 +0100 | [diff] [blame] | 53 | void call() |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 54 | { |
55 | if (functor) | ||||
56 | { | ||||
57 | (*functor)(); | ||||
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 58 | } |
59 | } | ||||
60 | |||||
61 | std::optional<F> functor; | ||||
62 | }; | ||||
63 | |||||
64 | } // namespace utils |