Advertisement
NikolaDimitroff

C++ Properties

May 30th, 2014
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template<typename T, typename P>
  6. class Property
  7. {
  8. private:
  9.     // Function pointers to the getter and setter
  10.     P(*getter)(const T&);
  11.     void(*setter)(T&, P);
  12.     // A reference to our owner
  13.     T& object;
  14. public:
  15.     Property(T& object, P(*getter)(const T&), void(*setter)(T&, P)) :
  16.         object(object), getter(getter), setter(setter)
  17.     { }
  18.  
  19.     Property(const Property& other) = delete;
  20.     Property(Property& other) = delete;
  21.  
  22.     operator P()
  23.     {
  24.         return this->getter(this->object);
  25.     }
  26.  
  27.     P operator=(const P& rhs)
  28.     {
  29.         this->setter(this->object, rhs);
  30.         return *this;
  31.     }
  32. };
  33.  
  34. class Animal
  35. {
  36. private:
  37.     int legsCount;
  38.     // Our allmighty getter
  39.     static int getLegsCount(const Animal& animal)
  40.     {
  41.         cout << "The getter got called" << endl;
  42.         return animal.legsCount;
  43.     }
  44.  
  45.     // And his friend the setter
  46.     static void setLegsCount(Animal& animal, int value)
  47.     {
  48.         cout << "The setter got called" << endl;
  49.         animal.legsCount = value;
  50.     }
  51.  
  52. public:
  53.     // Expose the property. That's safe since the property is immutable.
  54.     Property<Animal, int> LegsCount;
  55.     Animal(int legs) : LegsCount(*this, Animal::getLegsCount, Animal::setLegsCount)
  56.     {
  57.         this->legsCount = legs;
  58.     }
  59. };
  60.  
  61. int main()
  62. {
  63.     Animal cow(4);
  64.     cout << cow.LegsCount << endl;
  65.     cow.LegsCount = cow.LegsCount + 1; // Radioactive cows can grow another leg
  66.     cout << cow.LegsCount << endl;
  67.     cow.LegsCount = cow.LegsCount;
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement