diff --git a/source/mijin/util/common_macros.hpp b/source/mijin/util/common_macros.hpp new file mode 100644 index 0000000..ef8b088 --- /dev/null +++ b/source/mijin/util/common_macros.hpp @@ -0,0 +1,10 @@ + +#pragma once + +#if !defined(MIJIN_UTIL_COMMON_MACROS_HPP_INCLUDED) +#define MIJIN_UTIL_COMMON_MACROS_HPP_INCLUDED 1 + +#define MIJIN_CONCAT2(a, b) a ## b +#define MIJIN_CONCAT(a, b) MIJIN_CONCAT2(a, b) + +#endif // defined(MIJIN_UTIL_COMMON_MACROS_HPP_INCLUDED) \ No newline at end of file diff --git a/source/mijin/util/scope_guard.hpp b/source/mijin/util/scope_guard.hpp new file mode 100644 index 0000000..8a54469 --- /dev/null +++ b/source/mijin/util/scope_guard.hpp @@ -0,0 +1,42 @@ +#pragma once + +#if !defined(MIJIN_UTIL_SCOPE_GUARD_HPP_INCLUDED) +#define MIJIN_UTIL_SCOPE_GUARD_HPP_INCLUDED 1 + +#include +#include "./common_macros.hpp" + +#define MIJIN_SCOPE_EXIT_NAMED(name) \ +mijin::ScopeExitGuard name = [&]() + +#define MIJIN_SCOPE_EXIT MIJIN_SCOPE_EXIT_NAMED(MIJIN_CONCAT(MIJIN_CONCAT(scope_guard_, __LINE__), __)) + +namespace mijin +{ +class ScopeExitGuard +{ +private: + std::function func; +public: + template + inline ScopeExitGuard(TFunc&& func_) noexcept : func(std::forward(func_)) {} + ScopeExitGuard(const ScopeExitGuard&) noexcept = delete; + ScopeExitGuard(ScopeExitGuard&&) noexcept = delete; + inline ~ScopeExitGuard() noexcept + { + if (func) { + func(); + } + } + + ScopeExitGuard& operator=(const ScopeExitGuard&) noexcept = delete; + ScopeExitGuard& operator=(ScopeExitGuard&&) noexcept = delete; + + inline void reset() noexcept + { + func = {}; + } +}; +} + +#endif // defined(MIJIN_UTIL_SCOPE_GUARD_HPP_INCLUDED)