Created
March 10, 2018 02:56
-
-
Save daniellimws/c1b341024c9134dab5c63743d33faa7e to your computer and use it in GitHub Desktop.
Proper way to flip a bool
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
#include <memory> | |
template <typename T> | |
class ValueGetter { | |
public: | |
explicit ValueGetter(const T& value) : m_value{value} { | |
} | |
const T& get() const { | |
return m_value; | |
} | |
private: | |
const T& m_value; | |
}; | |
template <typename T> | |
class ValueSetter { | |
public: | |
explicit ValueSetter(T& value) : m_value{value} { | |
} | |
void set(T value) { | |
m_value = value; | |
} | |
private: | |
T& m_value; | |
}; | |
template <typename T> | |
static std::unique_ptr<ValueGetter<T>> MakeGetter(const T& value) { | |
return std::make_unique<ValueGetter<T>>(value); | |
} | |
template <typename T> | |
static std::unique_ptr<ValueSetter<T>> MakeSetter(T& value) { | |
return std::make_unique<ValueSetter<T>>(value); | |
} | |
class BooleanFlipper { | |
public: | |
explicit BooleanFlipper(bool& val) : m_getter{MakeGetter<bool>(val)}, m_setter{MakeSetter<bool>(val)} { | |
} | |
bool flip() { | |
if (m_getter->get()) { | |
m_setter->set(false); | |
} else { | |
m_setter->set(true); | |
} | |
return m_getter->get(); | |
} | |
private: | |
std::unique_ptr<ValueGetter<bool>> m_getter; | |
std::unique_ptr<ValueSetter<bool>> m_setter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment