fork download
  1. #include <cstdio>
  2. #include <memory>
  3.  
  4. struct Animal { virtual void sayHello() = 0; };
  5.  
  6. template<typename...> struct Dog; //forward decl.
  7.  
  8. //template to defer compilation of func body
  9. template<typename...> struct Cat : Animal {
  10. void sayHello() { printf("I am a Cat!\n"); new(this) Dog<>; }
  11. };
  12.  
  13. template<typename...> struct Dog : Animal {
  14. void sayHello() { printf("I am a Dog!\n"); new(this) Cat<>; }
  15. };
  16.  
  17. int main() {
  18. Cat<> cat;
  19. Animal& animal = cat;
  20.  
  21. animal.sayHello(); //I am a Cat
  22. animal.sayHello(); //I am a Dog
  23.  
  24. return 0;
  25. }
  26.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
I am a Cat!
I am a Dog!