Skip to content

Commit f2fc516

Browse files
committed
Execution/ScopeGuard
1 parent edfeede commit f2fc516

1 file changed

Lines changed: 26 additions & 6 deletions

File tree

modules/Execution/ScopeGuard.mpp

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,43 @@ import std;
44

55
export namespace CppUtils::Execution
66
{
7+
template<class Function>
78
class ScopeGuard final
89
{
910
public:
10-
explicit ScopeGuard(std::function<void()> onExit) noexcept:
11-
m_onExit{std::move(onExit)}
11+
template<class F>
12+
requires std::is_constructible_v<Function, F>
13+
explicit constexpr ScopeGuard(F&& onExit) noexcept(std::is_nothrow_constructible_v<Function, F>):
14+
m_onExit{std::forward<F>(onExit)}
1215
{}
1316

1417
ScopeGuard(const ScopeGuard&) = delete;
1518
auto operator=(const ScopeGuard&) -> ScopeGuard& = delete;
1619

17-
~ScopeGuard() noexcept
20+
constexpr ~ScopeGuard() noexcept
1821
{
19-
if (m_onExit)
20-
m_onExit();
22+
if (m_active)
23+
{
24+
if constexpr (requires { static_cast<bool>(m_onExit); })
25+
{
26+
if (m_onExit)
27+
std::invoke(m_onExit);
28+
}
29+
else
30+
std::invoke(m_onExit);
31+
}
32+
}
33+
34+
constexpr void dismiss() noexcept
35+
{
36+
m_active = false;
2137
}
2238

2339
private:
24-
std::function<void()> m_onExit;
40+
Function m_onExit;
41+
bool m_active = true;
2542
};
43+
44+
template<class Function>
45+
ScopeGuard(Function) -> ScopeGuard<Function>;
2646
}

0 commit comments

Comments
 (0)