Created
July 7, 2021 13:42
-
-
Save native-m/f40112cb2655427664c131a8637cc39b to your computer and use it in GitHub Desktop.
Simple Property Getter & Setter in C++
This file contains hidden or 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 <functional> | |
template<typename T> | |
class Property | |
{ | |
public: | |
using GetterFn = T&(); | |
using SetterFn = void(const T&); | |
template<typename Getter, typename Setter> | |
constexpr Property(Getter&& getter, Setter&& setter) noexcept : | |
m_getter(getter), | |
m_setter(setter) | |
{ | |
} | |
Property& operator=(const T& value) | |
{ | |
m_setter(value); | |
return *this; | |
} | |
operator T& () | |
{ | |
return m_getter(); | |
} | |
operator const T& () const | |
{ | |
return m_getter(); | |
} | |
private: | |
std::function<GetterFn> m_getter; | |
std::function<SetterFn> m_setter; | |
}; | |
/* | |
Usage | |
_____ | |
In-class declaration: | |
T = any type | |
Property<T> myProp { | |
[&]() -> T& { ... }, // Getter | |
[&](const T& value) { ... } // Setter | |
}; | |
Property access example: | |
other = myProp; // assign other variable from property | |
myProp = other; // assign property from other variable | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment