fork download
  1. #include <functional>
  2.  
  3. template <typename T>
  4. const T& default_get(T& value)
  5. { return value; }
  6.  
  7. template <typename T>
  8. const T& default_set(T& value, const T& rhs)
  9. { return value = rhs; }
  10.  
  11. template <typename T,
  12. std::function<const T& (T&)> get = default_get<T>,
  13. std::function<T& (T&, const T&)> set = default_set<T>>
  14. class property
  15. {
  16. public:
  17. operator const T& () const
  18. { return get(_value); }
  19.  
  20. T& operator= (const T& rhs)
  21. { return set(_value, rhs); }
  22.  
  23. private:
  24. T _value;
  25. };
  26.  
  27. const int& log(const int& value) { std::cout << value; return value; }
  28.  
  29. struct S
  30. {
  31. property<int,
  32. // log() used as decorator-style logging wrapper in properties
  33. [] (int& value) { log(default_get<int>(value)); },
  34. [] (int& value, const int& rhs) { log(default_set<int>(value, rhs)); }>
  35. field_name;
  36. };
  37.  
  38. /*
  39.  * The following is already possible with plain old functions, but cumbersome to write.
  40.  */
  41.  
  42. template <typename T,
  43. const T& (*get)(const T&) = default_get<T>,
  44. T& (*set)(T&, const T&) = default_set<T> >
  45. class property
  46. {
  47. public:
  48. operator const T& () const
  49. { return get(_value); }
  50.  
  51. T& operator= (const T& rhs)
  52. { return set(_value, rhs); }
  53.  
  54. private:
  55. T _value;
  56. };
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty