fork download
  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <typeinfo>
  4.  
  5. class Committer
  6. {
  7. public:
  8.  
  9. template <typename T>
  10. void mark_var_change(T *var)
  11. {
  12. mPointer = var;
  13. mTypeInfo = &typeid(T*);
  14. }
  15.  
  16. template <typename T>
  17. void commit_change(T new_value)
  18. {
  19. if (*mTypeInfo != typeid(T*)) {
  20. throw std::runtime_error("Bad type");
  21. }
  22. if (mPointer == nullptr) {
  23. throw std::runtime_error("nullptr was stocked");
  24. }
  25. *reinterpret_cast<T*>(mPointer) = new_value;
  26. }
  27.  
  28. private:
  29. void* mPointer = nullptr;
  30. const std::type_info* mTypeInfo = nullptr;
  31. };
  32.  
  33.  
  34. int main() {
  35. Committer c;
  36. int i;
  37. float f;
  38.  
  39. c.mark_var_change(&i);
  40. c.commit_change(42);
  41.  
  42. c.mark_var_change(&f);
  43. c.commit_change(4.2f);
  44.  
  45. std::cout << i << " " << f << std::endl;
  46.  
  47. try
  48. {
  49. c.mark_var_change(&i);
  50. c.commit_change(4.2f);
  51. }
  52. catch (const std::exception&e)
  53. {
  54. std::cout << e.what() << std::endl;
  55. }
  56. }
  57.  
  58.  
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
42 4.2
Bad type