fork download
  1. #include <iostream>
  2.  
  3.  
  4. template<class T>
  5. struct generic_property {
  6. virtual T getValue() const = 0;
  7. virtual void setValue(T const&) = 0;
  8. protected:
  9. virtual ~generic_property() {}
  10. };
  11. template<class D, class T, void(D::*set)(T const&), T(D::*get)() const>
  12. struct property:generic_property<T> {
  13. T getValue() const final {
  14. return (self->*get)();
  15. }
  16. void setValue(T const& t) final {
  17. (self->*set)(t);
  18. }
  19. property( D* s ):self(s) {}
  20.  
  21. // cannot usually safely copy/move/trivial:
  22. property() = delete;
  23. property( property const& ) = delete;
  24. property& operator=( property const& ) = delete;
  25. private:
  26. D* self = 0;
  27. };
  28.  
  29. struct Bob {
  30. void setFoo( int const& i ) { std::cout << i << " set\n"; }
  31. int getFoo() const { std::cout << 42 << " get\n"; return 42; }
  32. property<Bob, int, &Bob::setFoo, &Bob::getFoo> foo;
  33.  
  34. Bob():foo(this) {}
  35. };
  36.  
  37. int main() {
  38. Bob bob;
  39. std::cout << bob.foo.getValue() << "\n";
  40. bob.foo.setValue(3);
  41. generic_property<int>& foo = bob.foo;
  42. foo.setValue(4);
  43. }
Success #stdin #stdout 0s 4508KB
stdin
Standard input is empty
stdout
42 get
42
3 set
4 set