Sane C++ Libraries
C++ Platform Abstraction Libraries
Deferred.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Compiler.h"
5
6namespace SC
7{
10
15
37template <typename F>
39{
41 Deferred(F&& f) : f(forward<F>(f)) {}
42
45 {
46 if (armed)
47 f();
48 }
49
51 void disarm() { armed = false; }
52
53 private:
54 F f;
55 bool armed = true;
56};
57
60template <typename F>
62{
63 return Deferred<F>(forward<F>(f));
64}
65
67} // namespace SC
constexpr T && forward(typename TypeTraits::RemoveReference< T >::type &value)
Forwards an lvalue or an rvalue as an rvalue reference.
Definition: Compiler.h:272
Deferred< F > MakeDeferred(F &&f)
Creates a Deferred object holding a function that will be invoked at end of current scope.
Definition: Deferred.h:61
Executes a function at end of current scope (in the spirit of Zig defer keyword).
Definition: Deferred.h:39
Deferred(F &&f)
Constructs Deferred object with a functor F.
Definition: Deferred.h:41
void disarm()
Disarms the Deferred object, preventing function invocation on destruction.
Definition: Deferred.h:51
~Deferred()
Invokes the function F upon destruction, if disarm() has not been previously called.
Definition: Deferred.h:44