Squid::Tasks 1.0.0
C++14 coroutine-based task library for games
FunctionGuard.h
1#pragma once
2
50
51//--- User configuration header ---//
52#include "TasksConfig.h"
53
54NAMESPACE_SQUID_BEGIN
55
56template <typename tFn = std::function<void()>>
58{
59public:
60 FunctionGuard() = default;
61 FunctionGuard(nullptr_t)
62 {
63 }
64 FunctionGuard(tFn in_fn)
65 : m_fn(std::move(in_fn))
66 {
67 }
69 {
70 Execute();
71 }
72 FunctionGuard(FunctionGuard&& in_other) noexcept
73 : m_fn(std::move(in_other.m_fn))
74 {
75 in_other.Forget();
76 }
78 {
79 m_fn = std::move(in_other.m_fn);
80 in_other.Forget();
81 return *this;
82 }
83 FunctionGuard& operator=(nullptr_t) noexcept
84 {
85 Forget();
86 return *this;
87 }
88 operator bool() const
89 {
90 return IsBound();
91 }
92 bool IsBound() noexcept
93 {
94 return m_fn;
95 }
96 void Execute()
97 {
98 if(m_fn)
99 {
100 m_fn.value()();
101 Forget();
102 }
103 }
104 void Forget() noexcept
105 {
106 m_fn.reset();
107 }
108
109private:
110 std::optional<tFn> m_fn; // The function to call when this scope guard is destroyed
111};
112
114template <typename tFn>
116{
117 return FunctionGuard<tFn>(std::move(in_fn));
118}
119
121inline FunctionGuard<> MakeGenericFnGuard(std::function<void()> in_fn)
122{
123 return FunctionGuard<>(std::move(in_fn));
124}
125
126NAMESPACE_SQUID_END
127
Definition: FunctionGuard.h:58
FunctionGuard(FunctionGuard &&in_other) noexcept
Move constructor.
Definition: FunctionGuard.h:72
FunctionGuard & operator=(nullptr_t) noexcept
Null-pointer assignment operator (calls Forget() to clear the functor)
Definition: FunctionGuard.h:83
~FunctionGuard()
Destructor.
Definition: FunctionGuard.h:68
FunctionGuard & operator=(FunctionGuard< tFn > &&in_other) noexcept
Move assignment operator.
Definition: FunctionGuard.h:77
void Execute()
Executes and clears the functor (if bound)
Definition: FunctionGuard.h:96
void Forget() noexcept
Clear the functor (without calling it)
Definition: FunctionGuard.h:104
bool IsBound() noexcept
Returns whether functor has been bound to this FunctionGuard.
Definition: FunctionGuard.h:92
FunctionGuard(nullptr_t)
Default constructor.
Definition: FunctionGuard.h:61
FunctionGuard(tFn in_fn)
Functor constructor.
Definition: FunctionGuard.h:64
FunctionGuard MakeGenericFnGuard(std::function< void()> in_fn)
Create a generic function guard (preferable when re-assigning new functor values to the same variable...
Definition: FunctionGuard.h:121
FunctionGuard< tFn > MakeFnGuard(tFn in_fn)
Create a function guard (directly stores the concretely-typed functor in the FunctionGuard)
Definition: FunctionGuard.h:115