Skip to content

Instantly share code, notes, and snippets.

@native-m
Created July 7, 2021 13:42
Show Gist options
  • Save native-m/f40112cb2655427664c131a8637cc39b to your computer and use it in GitHub Desktop.
Save native-m/f40112cb2655427664c131a8637cc39b to your computer and use it in GitHub Desktop.
Simple Property Getter & Setter in C++
#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