fork download
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. #include <boost/any.hpp>
  5.  
  6. class Committer
  7. {
  8. public:
  9.  
  10. template <typename T>
  11. void mark_var_change(T *var)
  12. {
  13. mPointer = var;
  14. }
  15.  
  16. template <typename T>
  17. void commit_change(T new_value)
  18. {
  19. T* pointer = boost::any_cast<T*>(mPointer); // throw with bad type
  20. if (pointer == nullptr) {
  21. throw std::runtime_error("nullptr was stocked");
  22. }
  23. *pointer = new_value;
  24. }
  25.  
  26. private:
  27. boost::any mPointer;
  28. };
  29.  
  30.  
  31. int main() {
  32. Committer c;
  33. int i;
  34. float f;
  35.  
  36. c.mark_var_change(&i);
  37. c.commit_change(42);
  38.  
  39. c.mark_var_change(&f);
  40. c.commit_change(4.2f);
  41.  
  42. std::cout << i << " " << f << std::endl;
  43. }
  44.  
Success #stdin #stdout 0s 3280KB
stdin
Standard input is empty
stdout
42 4.2