MCRO
C++23 utilities for Unreal Engine.
Loading...
Searching...
No Matches
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 /** <pre>
19 * Used for lambdas which supposed to run only once. The first time it is converted to bool it returns true
20 * but every other times it will return false.
21 *
22 * Usage:
23 *
24 * using namespace BaseUtils;
25 * SomeEvent.AddLambda([once = FOnce()]
26 * {
27 * // Just use it inside a condition
28 * if (once) { ... }
29 *
30 * // exploiting short-circuit:
31 * if (MyCondition && once) { ... }
32 *
33 * // but this will not produce the expected result:
34 * if (once && MyCondition) { ... } // BAD
35 * }
36 * </pre>
37 */
38 struct FOnce
39 {
40 private:
41 bool bIsValid = true;
42
43 public:
44 FORCEINLINE FOnce() {}
45 FORCEINLINE FOnce(const FOnce& from) : bIsValid(from.bIsValid) {}
46 FORCEINLINE FOnce(FOnce&& from) noexcept
47 {
48 from.bIsValid = false;
49 }
50
51 FORCEINLINE operator bool()
52 {
53 const bool result = bIsValid;
54 bIsValid = false;
55 return result;
56 }
57
58 FORCEINLINE bool IsTriggered() const
59 {
60 return !bIsValid;
61 }
62
63 FORCEINLINE void Reset()
64 {
65 bIsValid = true;
66 }
67 };
68}
FORCEINLINE bool IsTriggered() const
Definition Once.h:58
FORCEINLINE FOnce(const FOnce &from)
Definition Once.h:45
FORCEINLINE FOnce(FOnce &&from) noexcept
Definition Once.h:46
FORCEINLINE void Reset()
Definition Once.h:63
FORCEINLINE FOnce()
Definition Once.h:44