fork download
  1. class Base {
  2. public:
  3. virtual void func1() = 0;
  4. virtual void func2() = 0;
  5.  
  6. virtual ~Base(){}
  7. };
  8.  
  9. #include <iostream>
  10. #include <memory>
  11.  
  12. class Derived : public Base
  13. {
  14. struct F1Strategy {
  15. virtual void f1Impl() = 0;
  16. virtual ~F1Strategy() {}
  17. };
  18.  
  19. struct Impl1 : F1Strategy {
  20. void f1Impl() override { std::cout << "one!\n"; }
  21. };
  22.  
  23. struct Impl2 : F1Strategy {
  24. void f1Impl() override { std::cout << "two?\n"; }
  25. };
  26.  
  27. std::unique_ptr<F1Strategy> f1Strategy;
  28. public:
  29. Derived()
  30. : f1Strategy(new Impl1())
  31. {}
  32.  
  33. void func1() override { f1Strategy->f1Impl(); }
  34.  
  35. void func2() override {
  36. static std::unique_ptr<F1Strategy> otherStrategy(new Impl2());
  37. f1Strategy.swap(otherStrategy);
  38. }
  39. };
  40.  
  41. int main() {
  42. std::unique_ptr<Base> pb(new Derived());
  43. pb->func1(); // ==> one!
  44. pb->func2(); //swap
  45. pb->func1(); // ==> two?
  46. pb->func1(); // ==> two?
  47. pb->func2(); //swap
  48. pb->func1(); // ==> one!
  49. }
  50.  
  51.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
one!
two?
two?
one!