fork download
  1. #include <iostream>
  2.  
  3. template <typename T, typename V>
  4. class Property
  5. {
  6. public:
  7. typedef V (T::*getter_type)() const;
  8. typedef void (T::*setter_type)(const V &value);
  9. Property(T *self, getter_type getter, setter_type setter) : self_(self), getter_(getter), setter_(setter) {}
  10. V get() const { return (self_->*getter_)(); }
  11. Property &set(const V &v) { (self_->*setter_)(v); return *this; }
  12. operator V() const { return get(); }
  13. Property &operator=(const V &v) { return set(v); }
  14. Property &operator+=(const V &v) { return set(get() += v); }
  15. private:
  16. T *self_;
  17. getter_type getter_;
  18. setter_type setter_;
  19. };
  20.  
  21. struct Integer
  22. {
  23. int value_;
  24. Integer(const int value) : value_(value) {}
  25. operator int() const { return value_; }
  26. Integer &operator =(const int value) { value_ = value; return *this; }
  27. Integer &operator +=(const int value) { value_ += value; return *this; }
  28. friend std::ostream &operator<<(std::ostream &os, const Integer &i) { os << i.value_; return os; }
  29. };
  30.  
  31. class Hoge
  32. {
  33. public:
  34. Hoge() : foo(this, &Hoge::get_foo, &Hoge::set_foo), foo_(0xdeadbeef) {}
  35. Property<Hoge, Integer> foo;
  36. Integer get_foo() const { return foo_; }
  37. void set_foo(const Integer &v) { foo_ = v; }
  38. private:
  39. Integer foo_;
  40. };
  41.  
  42. int main()
  43. {
  44. Hoge hoge;
  45. (hoge.foo = 123) += 456;
  46. std::cout << hoge.foo << std::endl;
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 2724KB
stdin
Standard input is empty
stdout
579