Last active
May 11, 2016 11:11
-
-
Save siliconbrain/875c04afc3aaa8800ef9e23eada01a44 to your computer and use it in GitHub Desktop.
emulating properties for 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
// | |
// 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