Skip to content

Instantly share code, notes, and snippets.

@AlexanderBrevig
Last active December 21, 2015 00:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlexanderBrevig/6217627 to your computer and use it in GitHub Desktop.
Save AlexanderBrevig/6217627 to your computer and use it in GitHub Desktop.
WProperty prototype
/*
||
|| @author Alexander Brevig <abrevig@wiring.org.co>
|| @url http://wiring.org.co/
|| @contribution Brett Hagman <bhagman@wiring.org.co>
|| @contribution Hernando Barragan <b@wiring.org.co>
||
|| @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
@bhagman
Copy link

bhagman commented Aug 13, 2013

I don't think we need to validation function any more in the plain-jane Property.

https://gist.github.com/AlexanderBrevig/6217627#file-gistfile1-txt-L26

Also, I think that we should name the validation functions in ConstrainedProperty and ConstantProperty to validator or validation.

What do you think?

@AlexanderBrevig
Copy link
Author

I completely agree, updated gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment