fork download
  1. #include <vector>
  2. #include <type_traits>
  3.  
  4. struct Parent { };
  5. struct A : Parent { };
  6. struct B : Parent { };
  7. struct C : Parent { };
  8. struct E : Parent { };
  9.  
  10. struct tag_none { };
  11. struct tag_A { };
  12. struct tag_B { };
  13. struct tag_C { };
  14.  
  15. template <typename T>
  16. struct component_tag { using type = tag_none; };
  17. template <>
  18. struct component_tag <A> { using type = tag_A; };
  19. template <>
  20. struct component_tag <B> { using type = tag_B; };
  21. template <>
  22. struct component_tag <C> { using type = tag_C; };
  23.  
  24. class D
  25. {
  26. public:
  27. template <typename T>
  28. void Store();
  29.  
  30. private:
  31. void Store_impl(void*, tag_none);
  32. void Store_impl(A* component, tag_A);
  33. void Store_impl(B* component, tag_B);
  34. void Store_impl(C* component, tag_C);
  35.  
  36. A *mA;
  37. B *mB;
  38. C *mC;
  39. std::vector<Parent*> mComponents;
  40. };
  41.  
  42. template <typename T>
  43. void D::Store()
  44. {
  45. using originalType = std::decay_t<std::remove_pointer_t<T> >;
  46. originalType* component = new originalType();
  47.  
  48. Store_impl(component, typename component_tag<originalType>::type { });
  49.  
  50. mComponents.push_back(component);
  51. }
  52.  
  53. void D::Store_impl(void*, tag_none)
  54. {
  55. // do nothing
  56. }
  57.  
  58. void D::Store_impl(A* component, tag_A)
  59. {
  60. mA = component;
  61. }
  62.  
  63. void D::Store_impl(B* component, tag_B)
  64. {
  65. mB = component;
  66. }
  67.  
  68. void D::Store_impl(C* component, tag_C)
  69. {
  70. mC = component;
  71. }
  72.  
  73.  
  74. int main()
  75. {
  76. A a;
  77. B b;
  78. C c;
  79. E e;
  80.  
  81. D obj;
  82.  
  83. obj.Store<A>();
  84. obj.Store<B>();
  85. obj.Store<C>();
  86.  
  87. obj.Store<E>();
  88. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Standard output is empty