fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. template <typename T, typename V>
  5. class Property
  6. {
  7. public:
  8. typedef const V &(T::*getter_type)() const;
  9. typedef void (T::*setter_type)(const V &value);
  10. Property(T *self, getter_type getter, setter_type setter) : self_(self), getter_(getter), setter_(setter) {}
  11. V get() const { return (self_->*getter_)(); }
  12. Property &set(const V &v) { (self_->*setter_)(v); return *this; }
  13. operator V() const { return get(); }
  14. Property &operator=(const V &v) { return set(v); }
  15. Property &operator+=(const V &v) { return set(get() += v); }
  16. V operator()() const { return get(); }
  17. friend std::ostream &operator<<(std::ostream &os, const Property &prop) { os << prop.get(); return os; }
  18. private:
  19. T *self_;
  20. getter_type getter_;
  21. setter_type setter_;
  22. };
  23.  
  24. class Hoge
  25. {
  26. public:
  27. Hoge() : str(this, &Hoge::get_str, &Hoge::set_str), str_("Hello") {}
  28. Property<Hoge, std::string> str;
  29. const std::string &get_str() const { return str_; }
  30. void set_str(const std::string &s) { str_ = s; }
  31. private:
  32. std::string str_;
  33. };
  34.  
  35. int main()
  36. {
  37. Hoge hoge;
  38. hoge.str += ", World!";
  39. std::cout << hoge.str().c_str() << std::endl;
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 2860KB
stdin
Standard input is empty
stdout
Hello, World!