fork download
  1. #include <iostream>
  2.  
  3. namespace so {
  4. template<typename _t_derived_>
  5. class _animal_ {
  6. private:
  7. using _derived_ = _t_derived_;
  8. public:
  9. void eat() const {
  10. static_cast<_derived_ const *>(this)->eat_impl();
  11. }
  12. };
  13.  
  14. class _dog_: public _animal_<_dog_> {
  15. friend class _animal_<_dog_> ;
  16. private:
  17. using _base_ = _animal_<_dog_>;
  18. protected:
  19. void eat_impl() const {
  20. std::cout << "dog's eating." << std::endl;
  21. }
  22. };
  23.  
  24. class _cat_: public _animal_<_cat_> {
  25. friend class _animal_<_cat_> ;
  26. private:
  27. using _base_ = _animal_<_cat_>;
  28. protected:
  29. void eat_impl() const {
  30. std::cout << "cat's eating." << std::endl;
  31. }
  32. };
  33.  
  34. template<typename _t_animal_>
  35. void feed(_t_animal_ const & _animal) {
  36. std::cout << "feeding an animal: ";
  37. _animal.eat();
  38. }
  39. } // namespace so
  40.  
  41. int main() {
  42. so::_dog_ dog_;
  43. so::_cat_ cat_;
  44.  
  45. so::feed(dog_);
  46. so::feed(cat_);
  47.  
  48. return (0);
  49. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
feeding an animal: dog's eating.
feeding an animal: cat's eating.