fork download
  1. #include <iostream>
  2.  
  3. template<class Derived>
  4. class CRTP {
  5. protected:
  6. Derived * derived_this() {
  7. return static_cast<Derived *>(this);
  8. }
  9. };
  10.  
  11. template<class Derived>
  12. struct Parent : public CRTP<Derived> {
  13. private:
  14. using CRTP<Derived>::derived_this;
  15. public:
  16. int y() {
  17. return derived_this()->x();
  18. }
  19. };
  20.  
  21. struct Child : public Parent<Child> {
  22. int x() {
  23. return 5;
  24. }
  25. int z() {
  26. return y();
  27. }
  28. };
  29.  
  30. int main() {
  31. std::cout << Child().z() << std::endl;
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
5