fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4.  
  5. template<typename T>
  6. class AT
  7. {
  8. public:
  9. virtual T get() const = 0;
  10. };
  11.  
  12. class IT : public AT<int>
  13. {
  14. public:
  15. int get() const { std::cout << "IT get" << std::endl; return 1; }
  16. };
  17.  
  18. class ST : public AT<std::string>
  19. {
  20. public:
  21. std::string get() const { std::cout << "ST get" << std::endl; return "ST"; }
  22. };
  23.  
  24. class A
  25. {
  26. public:
  27. A(){}
  28. virtual ~A() {}
  29. //protected:
  30. void common() { std::cout << "A common" << std::endl; }
  31. };
  32.  
  33. class B : public A , public IT
  34. {
  35. public:
  36. B(){}
  37. virtual ~B() {}
  38. void get() { IT::get(); }
  39. };
  40.  
  41. class C : public A , public ST
  42. {
  43. public:
  44. C(){}
  45. virtual ~C(){}
  46. void get() { ST::get(); }
  47. };
  48.  
  49. enum TYPE { NUMBER, STRING };
  50.  
  51. int main()
  52. {
  53. std::map<int, A*(*)()> makeAMap;
  54. makeAMap[NUMBER] = []() -> A* { std::cout << "making B" << std::endl; return new B; };
  55. makeAMap[STRING] = []() -> A* { std::cout << "making C" << std::endl; return new C; };
  56. //...
  57.  
  58. std::map<int, void(*)(A*)> getFuncMap;
  59. getFuncMap[NUMBER] = [](A *item){ static_cast<B*>(item)->get(); };
  60. getFuncMap[STRING] = [](A *item){ static_cast<C*>(item)->get(); };
  61. //...
  62.  
  63. int type;
  64. A* item;
  65.  
  66. type = 0;
  67. item = makeAMap[type]();
  68. //...
  69. item->common();
  70. getFuncMap[type](item);
  71. //...
  72. delete item;
  73.  
  74. type = 1;
  75. item = makeAMap[type]();
  76. //...
  77. item->common();
  78. getFuncMap[type](item);
  79. //...
  80. delete item;
  81.  
  82. return 0;
  83. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
making B A common IT get making C A common ST get