Skip to content

Instantly share code, notes, and snippets.

@siliconbrain
Last active May 11, 2016 11:11
Show Gist options
  • Save siliconbrain/875c04afc3aaa8800ef9e23eada01a44 to your computer and use it in GitHub Desktop.
Save siliconbrain/875c04afc3aaa8800ef9e23eada01a44 to your computer and use it in GitHub Desktop.
emulating properties for C++
//
// Usage:
// class Foo
// {
// int bar;
//
// public:
// property<int> Bar;
//
// Foo(int bar)
// : bar(bar)
// , Bar(/* getter: */ [this]() { return this->bar; },
// /* setter: */ [this](int value) { this->bar = value; })
// {
// // ...
// }
// };
//
// // ...
// {
// Foo foo(13);
// std::cout << foo.Bar << std::endl; // prints 13
// foo.Bar = 42;
// std::cout << foo.Bar << std::endl; // prints 42
// }
//
template<typename T>
struct property
{
template<typename getter_t, typename setter_t>
property(getter_t getter, setter_t setter)
{
_getter = getter;
_setter = setter;
}
operator T() const
{
return _getter();
}
property& operator=(const T& value)
{
_setter(value);
return *this;
}
private:
std::function<T()> _getter;
std::function<void(const T&)> _setter;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment