fork download
  1. #include <type_traits>
  2. #include <iostream>
  3.  
  4. //classes
  5. struct A { virtual ~A(){} virtual void print(){std::cout << "A\n";}};
  6. struct B : A { virtual void print(){std::cout << "B\n";}};
  7. struct C : A { virtual void print(){std::cout << "C\n";}};
  8. struct D : A { virtual void print(){std::cout << "D\n";}};
  9.  
  10. //polymorphic local forwarder
  11. template<class Type, class FuncType>
  12. auto poly_local(FuncType func) -> decltype(func(std::declval<Type&>()))
  13. {
  14. Type local;
  15. return func(local);
  16. }
  17.  
  18. //test function
  19. char dowork(A& a) {
  20. a.print();
  21. return '8';
  22. }
  23. //test functionoid with parameters
  24. struct dowork2 {
  25. int parameter;
  26. explicit dowork2(int p) :parameter(p) {}
  27. int operator()(A& a) const{
  28. a.print();
  29. std::cout << parameter << '\n';
  30. return parameter;
  31. }
  32. };
  33.  
  34. //demo
  35. int main() {
  36. int some_var = 2;
  37.  
  38. switch (some_var) {
  39. case 1: poly_local<A>(dowork); break;
  40. case 2: poly_local<B>(dowork); break;
  41. default: poly_local<C>(dowork); break;
  42. }
  43.  
  44. switch (some_var) {
  45. case 1: poly_local<B>(dowork2(3)); break;
  46. case 2: poly_local<C>(dowork2(2)); break;
  47. default: poly_local<A>(dowork2(1)); break;
  48. }
  49. return 0;
  50. }
Success #stdin #stdout 0s 2928KB
stdin
Standard input is empty
stdout
B
C
2