Skip to content

Instantly share code, notes, and snippets.

@daniellimws
Created March 10, 2018 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniellimws/c1b341024c9134dab5c63743d33faa7e to your computer and use it in GitHub Desktop.
Save daniellimws/c1b341024c9134dab5c63743d33faa7e to your computer and use it in GitHub Desktop.
Proper way to flip a bool
#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