fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. template <typename T, typename V>
  5. class Property
  6. {
  7. public:
  8. typedef 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. private:
  18. T *self_;
  19. getter_type getter_;
  20. setter_type setter_;
  21. };
  22.  
  23. class Hoge
  24. {
  25. public:
  26. Hoge() : str(this, &Hoge::get_str, &Hoge::set_str), str_("Hello") {}
  27. Property<Hoge, std::string> str;
  28. std::string get_str() const { return str_; }
  29. void set_str(const std::string &s) { str_ = s; }
  30. private:
  31. std::string str_;
  32. };
  33.  
  34. int main()
  35. {
  36. Hoge hoge;
  37. hoge.str += ", World!";
  38. std::cout << hoge.str->c_str() << std::endl;
  39. return 0;
  40. }
  41.  
stdin
Standard input is empty
compilation info
prog.cpp: In member function ‘V* Property<T, V>::operator->() const [with T = Hoge, V = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]’:
prog.cpp:38:   instantiated from here
prog.cpp:16: warning: taking address of temporary
stdout
Hello, World!