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 | { |
| 25 | clear(); |
| 26 | } |
| 27 | |
| 28 | template <class U> |
| 29 | Ensure& operator=(U&& other) |
| 30 | { |
| 31 | clear(); |
| 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 | { |
| 40 | clear(); |
| 41 | return *this; |
| 42 | } |
| 43 | |
| 44 | Ensure& operator=(const Ensure&) = delete; |
| 45 | |
Krzysztof Grobelny | 973b4bb | 2022-04-25 17:07:27 +0200 | [diff] [blame] | 46 | explicit operator bool() const |
| 47 | { |
| 48 | return static_cast<bool>(functor); |
| 49 | } |
| 50 | |
Krzysztof Grobelny | f7ea299 | 2022-01-27 11:04:58 +0100 | [diff] [blame] | 51 | private: |
| 52 | void clear() |
| 53 | { |
| 54 | if (functor) |
| 55 | { |
| 56 | (*functor)(); |
| 57 | functor = std::nullopt; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | std::optional<F> functor; |
| 62 | }; |
| 63 | |
| 64 | } // namespace utils |