fork(2) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. template<class T>
  7. class Base
  8. {
  9. public:
  10. auto VirtualFuncInterface()// How to write in C++11 or older style?
  11. {
  12. return static_cast<T*>(this)->VirtualFuncImpl();
  13. }
  14. };
  15. class Derived : public Base<Derived>
  16. {
  17. public:
  18. bool VirtualFuncImpl()
  19. {
  20. cout << "Derived" << endl;
  21. return true;
  22. }
  23. };
  24. class Derived2 : public Base<Derived2>
  25. {
  26. public:
  27. double VirtualFuncImpl()
  28. {
  29. cout << "Derived2" << endl;
  30. return 94.87;
  31. }
  32. };
  33. template<class T>
  34. void Poly(Base<T>* b)
  35. {
  36. cout<<b->VirtualFuncInterface()<<endl;
  37. }
  38. int main()
  39. {
  40. Base<Derived2>* ptr = new Derived2;
  41. Base<Derived>* ptr2 = new Derived;
  42. Poly(ptr);
  43. Poly(ptr2);
  44. return 0;
  45. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
Derived2
94.87
Derived
1