Created
April 27, 2017 01:01
-
-
Save elementbound/cd3edefffc63b3360757c85f7bc74254 to your computer and use it in GitHub Desktop.
Properties in C++
This file contains 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
template <typename T, typename Class, T(Class::*Getter)(), void(Class::*Setter)(const T&)> | |
class _property { | |
typedef _property<T, Class, Getter, Setter> self_type; | |
typedef T value_type; | |
typedef Class parent_type; | |
decltype(Getter) getter_func = Getter; | |
decltype(Setter) setter_func = Setter; | |
private: | |
value_type _value; | |
parent_type* _parent; | |
public: | |
_property() = default; | |
_property(const self_type&) = default; | |
~_property() = default; | |
_property(parent_type* p=nullptr): | |
_value(), | |
_parent(p) | |
{}; | |
value_type operator()() { | |
return (this->_parent->*getter_func)(); | |
} | |
operator value_type() { | |
return (this->_parent->*getter_func)(); | |
} | |
self_type& operator=(const value_type& rhs) { | |
(this->_parent->*setter_func)(rhs); | |
return *this; | |
} | |
}; | |
#define property(type, klass, name, getter_body, setter_body) \ | |
private: \ | |
type _##name##_getter() { \ | |
getter_body; \ | |
} \ | |
void _##name##_setter(const type& value) { \ | |
setter_body; \ | |
} \ | |
\ | |
public: \ | |
_property<type, klass, _##name##_getter, _##name##_setter> name; | |
class weight { | |
public: | |
float _weight; | |
public: | |
property(float, weight, kilos, | |
return this->_weight;, | |
this->_weight = value; | |
) | |
property(float, weight, pounds, | |
return this->_weight / 0.4535f;, | |
this->_weight = value * 0.4535f; | |
) | |
weight(): | |
kilos(this), | |
pounds(this) | |
{} | |
~weight() = default; | |
}; | |
#include <iostream> | |
int main() { | |
weight w; | |
w.kilos = 8.0f; | |
std::cout << w.kilos << " kilos = " << w.pounds << " pounds" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment