Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- template<typename T, typename P>
- class Property
- {
- private:
- // Function pointers to the getter and setter
- P(*getter)(const T&);
- void(*setter)(T&, P);
- // A reference to our owner
- T& object;
- public:
- Property(T& object, P(*getter)(const T&), void(*setter)(T&, P)) :
- object(object), getter(getter), setter(setter)
- { }
- Property(const Property& other) = delete;
- Property(Property& other) = delete;
- operator P()
- {
- return this->getter(this->object);
- }
- P operator=(const P& rhs)
- {
- this->setter(this->object, rhs);
- return *this;
- }
- };
- class Animal
- {
- private:
- int legsCount;
- // Our allmighty getter
- static int getLegsCount(const Animal& animal)
- {
- cout << "The getter got called" << endl;
- return animal.legsCount;
- }
- // And his friend the setter
- static void setLegsCount(Animal& animal, int value)
- {
- cout << "The setter got called" << endl;
- animal.legsCount = value;
- }
- public:
- // Expose the property. That's safe since the property is immutable.
- Property<Animal, int> LegsCount;
- Animal(int legs) : LegsCount(*this, Animal::getLegsCount, Animal::setLegsCount)
- {
- this->legsCount = legs;
- }
- };
- int main()
- {
- Animal cow(4);
- cout << cow.LegsCount << endl;
- cow.LegsCount = cow.LegsCount + 1; // Radioactive cows can grow another leg
- cout << cow.LegsCount << endl;
- cow.LegsCount = cow.LegsCount;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement