fork download
  1.  
  2. #include <iostream>
  3.  
  4.  
  5. template<typename T>
  6. class Enforcer: public T
  7. {
  8. public:
  9. template<typename... Args>
  10. Enforcer(Args&&... arg): T(std::forward<Args>(arg)...)
  11. {
  12.  
  13. }
  14.  
  15. void init() override
  16. {
  17. T::init();
  18. T::BaseClass::init();
  19. }
  20. };
  21.  
  22. class Base
  23. {
  24. public:
  25. virtual void init() = 0;
  26. private:
  27. bool initialized = false;
  28. };
  29.  
  30. void Base::init()
  31. {
  32. std::cout << "Called from base!\n";
  33. initialized = true;
  34. }
  35.  
  36. class Derived: public Base
  37. {
  38. friend class Enforcer<Derived>;
  39. public:
  40. void init() override
  41. {
  42. std::cout << "Called from derived!\n";
  43. }
  44. private:
  45. Derived()
  46. {
  47. }
  48. private:
  49. using BaseClass = Base;
  50. private:
  51. bool initialized = false;
  52. };
  53.  
  54. int main()
  55. {
  56. Enforcer<Derived> d;
  57. d.init();
  58. }
  59.  
  60.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Called from derived!
Called from base!