fork download
  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4.  
  5. template <typename T>
  6. class Property{
  7. private:
  8.  
  9. T val;
  10.  
  11. std::function<void(T& v,const T& newV)> setFN = nullptr;
  12.  
  13. public:
  14.  
  15. void setter(decltype(setFN) newSetter){
  16. setFN = newSetter;
  17. }
  18.  
  19. void set(const T& newVal){
  20. if(!setFN)
  21. val = newVal;
  22. else
  23. setFN(val,newVal);
  24. }
  25.  
  26. T get(){
  27. return val;
  28. }
  29. };
  30.  
  31. int main() {
  32.  
  33. Property<int> x;
  34.  
  35. x.set(5);
  36. std::cout << x.get() << std::endl;
  37.  
  38. x.setter([](int& v, const int& newV){std::cout << "Setter called\n"; v=newV;});
  39.  
  40. x.set(2);
  41. std::cout << x.get() << std::endl;
  42. // your code goes here
  43. return 0;
  44. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
5
Setter called
2