fork download
  1. #include <iostream>
  2.  
  3. void doSomething (int x) {std::cout << "Do something with " << x << std::endl;}
  4.  
  5. template <typename T, typename D>
  6. void helper(const D& base)
  7. {
  8. // Code A
  9. if (base.T::foo() < 6) {
  10. // Code B
  11. }
  12. doSomething (base.T::goo());
  13. // Code C
  14. if (base.T::hoo() > 10) {
  15. // Code D
  16. }
  17. }
  18.  
  19. struct Base {
  20. virtual ~Base() = default;
  21. virtual int foo() const {return 5;}
  22. virtual int goo() const {return 6;}
  23. virtual int hoo() const {return 7;}
  24.  
  25. void noTemplatePattern() const
  26. {
  27. helper<Base>(*this);
  28. }
  29. #if 0 // activate this code if you want this method accessible from base
  30. virtual void templatePattern() const = 0;
  31. #endif
  32. };
  33.  
  34. template <typename Derived>
  35. struct BaseImpl : Base {
  36. void templatePattern() const /*override final*/ {
  37. helper<Derived>(static_cast<const Derived&>(*this));
  38. }
  39. };
  40.  
  41. struct Derived : BaseImpl<Derived> {
  42. virtual int foo() const override {return 12;}
  43. virtual int goo() const override {return 13;}
  44. virtual int hoo() const override {return 14;}
  45. };
  46.  
  47. int main() {
  48. Derived d;
  49. d.noTemplatePattern();
  50. d.templatePattern();
  51. }
  52.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
Do something with 6
Do something with 13