Created
February 3, 2022 11:54
-
-
Save ziocleto/e649a6bdb86576620f36ef002089b963 to your computer and use it in GitHub Desktop.
Simple "Test and Set" Functor template to avoid working with naked variables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
// Author: Dado, le Grand Fromage | |
// | |
// The purpose of this extremely simple template class is to address situations like these: | |
// | |
// if ( MyVariable ) | |
// { | |
// [...] | |
// MyVariable = false; | |
// } | |
// | |
// You don't want to play around with naked variables like if that's their only purpose. | |
// You can make them into a function, and precisely into a functor in this case | |
// | |
// The operator() will act as a switch returning the old value, so the code above will effectively become: | |
// | |
// if ( MyVariable() ) | |
// { | |
// [...] | |
// } | |
// No need to reset the variable to false as that will be flip/flopped inside the operator() function | |
// By passing a parameter to the operator() function it will act as a "set" | |
// | |
// MyVariable = true; | |
// | |
// MyVariable(true) | |
// | |
// The functor uses a default value of 0, so it might not be suitable for types that cannot be casted to that | |
// I might consider adding type traits Concepts, C++20 fashion. | |
// | |
// Warning: This code uses UnrealEngine Pascal BS coding standard, don't ask why, I'm already crying. | |
template <typename T> | |
class TTestAndSetFunctor | |
{ | |
public: | |
T operator()( T NewValue = T{0} ) | |
{ | |
T OrigValue = Value; | |
Value = NewValue; | |
return OrigValue; | |
} | |
private: | |
T Value=T{0}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment