Properties
Verfasst: Mi Apr 24, 2013 1:28 pm
Hi, ich hab' mir mal Gedanken gemacht, wie man Properties in C++ realisieren könnte. Über den Vorteil lässt sich streiten, dennoch würde mich mal eure Meinung zu meiner einfachen Implementierung interessieren
Ein Beispiel könnte so aussehen:
LG Glocke
/EDIT: Prinzipiell ließe sich auch Read-Only / Write-Only realisieren - dann aber imho nur zur Laufzeit.

Code: Alles auswählen
template <typename Type, typename Parent>
class property {
protected:
Parent* parent;
Type (Parent::*getter)();
void (Parent::*setter)(Type);
Type get() {
return (this->parent->*getter)();
}
void set(Type value) {
(this->parent->*setter)(value);
}
public:
property(Parent* parent, Type (Parent::*getter)(), void (Parent::*setter)(Type))
: parent(parent)
, getter(getter)
, setter(setter) {
}
property<Type, Parent>& operator=(Type value) {
this->set(value);
}
property<Type, Parent>& operator+=(Type value) {
Type current = this->get();
current += value;
this->set(current);
}
property<Type, Parent>& operator-=(Type value) {
Type current = this->get();
current -= value;
this->set(current);
}
property<Type, Parent>& operator*=(Type value) {
Type current = this->get();
current *= value;
this->set(current);
}
property<Type, Parent>& operator/=(Type value) {
Type current = this->get();
current /= value;
this->set(current);
}
// @todo: Weitere Operatoren: + - * / == != <= => < >
operator Type() {
return this->get();
}
};
Code: Alles auswählen
class Example2 {
protected:
int _value;
int getValue() {
return this->_value;
}
void setValue(int value) {
if (value < -10) { value = -10; }
if (value > 100) { value = 100; }
this->_value = value;
}
public:
// Deklaration der Property
property<int, Example2> value;
Example2()
// Wert initialisieren
: _value(0)
// Property initialisieren
, value(this, &Example2::getValue, &Example2::setValue) {
}
};
// ----------------------------------------------------------------------------
int main() {
Example2 e;
e.value = 5;
e.value *= 2;
int i = e.value;
std::cout << i << "\n";
}
/EDIT: Prinzipiell ließe sich auch Read-Only / Write-Only realisieren - dann aber imho nur zur Laufzeit.