Last active
December 21, 2015 00:08
-
-
Save AlexanderBrevig/6217627 to your computer and use it in GitHub Desktop.
WProperty prototype
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
/* | |
|| | |
|| @author Alexander Brevig <[email protected]> | |
|| @url http://wiring.org.co/ | |
|| @contribution Brett Hagman <[email protected]> | |
|| @contribution Hernando Barragan <[email protected]> | |
|| | |
|| @description | |
|| | A public field wrapper for providing assignment safe guards | |
|| # | |
|| | |
|| @license Please see cores/Common/License.txt. | |
|| | |
*/ | |
#ifndef WPROPERTY_H | |
#define WPROPERTY_H | |
/* | |
|| A basic property, semantically equivalent of a regular public field | |
*/ | |
template<typename T> | |
class Property | |
{ | |
public: | |
Property() { } | |
Property<T> &operator=(const T rhs) { | |
value = rhs; | |
return *this; | |
} | |
operator T() { | |
return value; | |
} | |
private: | |
T value; | |
}; | |
/* | |
|| A property that implement assignment rules | |
*/ | |
template<typename T> | |
class ConstrainedProperty | |
{ | |
public: | |
typedef bool (*comp_fn)(T); | |
ConstrainedProperty(comp_fn _comparator) : comparator(_comparator) { } | |
ConstrainedProperty<T> &operator=(const T rhs) { | |
if (comparator == 0 || comparator(rhs)) { | |
value = rhs; | |
} | |
return *this; | |
} | |
operator T() { return value; } | |
operator T() const { return T(); } | |
private: | |
T value; | |
comp_fn comparator; | |
}; | |
/* | |
|| A constant property for reading a private member field | |
*/ | |
template<typename T> | |
class ConstantProperty | |
{ | |
public: | |
typedef bool (*comp_fn)(T); | |
ConstantProperty(T &ref) : validator(0), valuePointer(&ref) { } | |
ConstantProperty(comp_fn _validator, T &ref) : validator(_validator), valuePointer(&ref) { } | |
ConstantProperty<T> &operator=(const T rhs) { | |
if (validator == 0 || validator(rhs)) { | |
if (valuePointer != 0) { | |
*valuePointer = rhs; | |
} | |
} | |
return *this; | |
} | |
operator T() { return *valuePointer; } | |
operator T() const { return T(); } | |
private: | |
T *valuePointer; | |
comp_fn validator; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I completely agree, updated gist