liblcf
Loading...
Searching...
No Matches
scope_guard.h
Go to the documentation of this file.
1/*
2 * This file is part of liblcf. Copyright (c) 2020 liblcf authors.
3 * https://github.com/EasyRPG/liblcf - https://easyrpg.org
4 *
5 * liblcf is Free/Libre Open Source Software, released under the MIT License.
6 * For the full copyright and license information, please view the COPYING
7 * file that was distributed with this source code.
8 */
9
10#ifndef LCF_SCOPE_GUARD_H
11#define LCF_SCOPE_GUARD_H
12#include <utility>
13
14template <typename F>
16 public:
17 ScopeGuard() = default;
18 explicit ScopeGuard(const F& f) : _f(f), _active(true) {}
19 explicit ScopeGuard(F&& f) : _f(std::move(f)), _active(true) {}
20
21 ScopeGuard(const ScopeGuard&) = delete;
22 ScopeGuard& operator=(const ScopeGuard&) = delete;
23
25 : _f(std::move(o._f)), _active(true) { o._active = false; }
27
29
30 void Fire() noexcept;
31 void Dismiss() noexcept;
32 bool IsActive() noexcept;
33 private:
34 F _f;
35 bool _active = false;
36};
37
38template <typename F>
39inline ScopeGuard<F> makeScopeGuard(F&& f) {
40 return ScopeGuard<F>(std::forward<F>(f));
41}
42
43template <typename F>
44inline void ScopeGuard<F>::Fire() noexcept {
45 if (_active) {
46 _f();
47 Dismiss();
48 }
49}
50
51template <typename F>
52inline void ScopeGuard<F>::Dismiss() noexcept {
53 _active = false;
54}
55
56template <typename F>
57inline bool ScopeGuard<F>::IsActive() noexcept {
58 return _active;
59}
60
61#endif
ScopeGuard()=default
void Fire() noexcept
Definition: scope_guard.h:44
ScopeGuard(const F &f)
Definition: scope_guard.h:18
ScopeGuard & operator=(ScopeGuard &&)=delete
bool IsActive() noexcept
Definition: scope_guard.h:57
void Dismiss() noexcept
Definition: scope_guard.h:52
ScopeGuard(ScopeGuard &&o)
Definition: scope_guard.h:24
bool _active
Definition: scope_guard.h:35
ScopeGuard(const ScopeGuard &)=delete
ScopeGuard & operator=(const ScopeGuard &)=delete
ScopeGuard(F &&f)
Definition: scope_guard.h:19
STL namespace.
ScopeGuard< F > makeScopeGuard(F &&f)
Definition: scope_guard.h:39