MCRO
C++23 utilities for Unreal Engine.
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages Concepts
Once.h
Go to the documentation of this file.
1/** @noop License Comment
2 * @file
3 * @copyright
4 * This Source Code is subject to the terms of the Mozilla Public License, v2.0.
5 * If a copy of the MPL was not distributed with this file You can obtain one at
6 * https://mozilla.org/MPL/2.0/
7 *
8 * @author David Mórász
9 * @date 2025
10 */
11
12#pragma once
13
14#include "CoreMinimal.h"
15
16namespace Mcro::Once
17{
18 /**
19 * @brief
20 * Used for lambdas which supposed to run only once. The first time it is converted to bool it returns true
21 * but every other times it will return false.
22 *
23 * Usage:
24 * @code
25 * using namespace BaseUtils;
26 * SomeEvent.AddLambda([once = FOnce()]
27 * {
28 * // Just use it inside a condition
29 * if (once) { ... }
30 *
31 * // exploiting short-circuit:
32 * if (MyCondition && once) { ... }
33 *
34 * // but this will not produce the expected result:
35 * if (once && MyCondition) { ... } // BAD
36 * }
37 * @endcode
38 */
39 struct FOnce
40 {
41 private:
42 bool bIsValid = true;
43
44 public:
45 FORCEINLINE FOnce() {}
46 FORCEINLINE FOnce(const FOnce& from) : bIsValid(from.bIsValid) {}
47 FORCEINLINE FOnce(FOnce&& from) noexcept
48 {
49 from.bIsValid = false;
50 }
51
52 FORCEINLINE operator bool()
53 {
54 const bool result = bIsValid;
55 bIsValid = false;
56 return result;
57 }
58
59 FORCEINLINE bool IsTriggered() const
60 {
61 return !bIsValid;
62 }
63
64 FORCEINLINE void Reset()
65 {
66 bIsValid = true;
67 }
68 };
69}
Used for lambdas which supposed to run only once. The first time it is converted to bool it returns t...
Definition Once.h:40
FORCEINLINE bool IsTriggered() const
Definition Once.h:59
FORCEINLINE FOnce(const FOnce &from)
Definition Once.h:46
FORCEINLINE FOnce(FOnce &&from) noexcept
Definition Once.h:47
FORCEINLINE void Reset()
Definition Once.h:64
FORCEINLINE FOnce()
Definition Once.h:45