fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <functional>
  4. #include <memory>
  5.  
  6. class MyClass
  7. {
  8. float myFloat;
  9. public:
  10. MyClass(float f):myFloat(f){}
  11.  
  12. void myFunc(int arg1)
  13. {
  14. std::cout << arg1 << ", " << myFloat << '\n';
  15. }
  16. };
  17.  
  18. class MyContainer
  19. {
  20. public:
  21. MyClass* object;
  22. };
  23.  
  24. // DelayedCaller implementation
  25. class DelayedCaller
  26. {
  27. public:
  28. template <typename TFunction, typename... TArgs>
  29. static std::shared_ptr<DelayedCaller> setup(TFunction&& a_func,
  30. TArgs&&... a_args)
  31. {
  32. return std::shared_ptr<DelayedCaller>(new DelayedCaller(
  33. std::bind(std::forward<TFunction>(a_func),
  34. std::forward<TArgs>(a_args)...)));
  35. }
  36. void call() const { func_(); }
  37.  
  38. private:
  39. using func_type = std::function<void()>;
  40. DelayedCaller(func_type&& a_ft) : func_(std::forward<func_type>(a_ft)) {}
  41. func_type func_;
  42. };
  43.  
  44. int main()
  45. {
  46. MyContainer container;
  47. MyClass c1(45.6);
  48. container.object = &c1;
  49. // the next line is the critical one. Instead of myFunc being called
  50. // on the current value of container.object, it should be called on
  51. // the one container.object is holding when caller is called.
  52. auto caller(DelayedCaller::setup(&MyClass::myFunc, std::ref(container.object), 123));
  53.  
  54. caller->call();
  55.  
  56. MyClass c2(22.8);
  57. container.object = &c2;
  58. caller->call();
  59. }
Success #stdin #stdout 0s 4288KB
stdin
Standard input is empty
stdout
123, 45.6
123, 22.8