fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <string>
  4.  
  5. template <typename T>
  6. class attr
  7. {
  8. std::function<T()> const get;
  9. std::function<void(T)> const set;
  10.  
  11. public:
  12. template <typename Get, typename Set>
  13. attr(Get get_, Set set_)
  14. : get(get_),
  15. set(set_)
  16. {}
  17.  
  18. operator T ()
  19. {
  20. return get();
  21. }
  22.  
  23. template <typename U>
  24. attr& operator= (U value)
  25. {
  26. set(value);
  27. return *this;
  28. }
  29. };
  30.  
  31. class person {
  32. std::string m_name;
  33. int m_age;
  34.  
  35. public:
  36. attr<std::string> name {
  37. [this]() -> std::string
  38. {
  39. std::cout << "getting name: " << m_name << std::endl;
  40. return this->m_name;
  41. },
  42. [this](std::string value)
  43. {
  44. std::cout << "setting name: " << value << std::endl;
  45. this->m_name = value;
  46. }
  47. };
  48.  
  49. attr<int> age {
  50. [this]() -> int
  51. {
  52. std::cout << "getting age: " << m_age << std::endl;
  53. return this->m_age;
  54. },
  55. [this](int value)
  56. {
  57. std::cout << "setting age: " << value << std::endl;
  58. this->m_age = value;
  59. }
  60. };
  61. };
  62.  
  63. int main()
  64. {
  65. person someone;
  66. someone.name = "John Doe";
  67. someone.age = 42;
  68.  
  69. std::cout << "Name: " << (std::string)someone.name << std::endl; // Here's a potential issue with the wrapper. Take out the cast, it won't work.
  70. std::cout << "Age: " << someone.age << std::endl;
  71.  
  72. return someone.age;
  73. }
  74.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:36:23: error: function definition does not declare parameters
prog.cpp:49:15: error: function definition does not declare parameters
prog.cpp: In function 'int main()':
prog.cpp:66:13: error: 'class person' has no member named 'name'
prog.cpp:67:13: error: 'class person' has no member named 'age'
prog.cpp:69:51: error: 'class person' has no member named 'name'
prog.cpp:70:38: error: 'class person' has no member named 'age'
prog.cpp:72:20: error: 'class person' has no member named 'age'
stdout
Standard output is empty