fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <utility>
  4. #include <memory>
  5. using namespace std;
  6.  
  7. class Base
  8. {
  9. public:
  10. enum
  11. {
  12. BaseClass,
  13. Derived1Class,
  14. Derived2Class
  15. };
  16.  
  17. Base() {}
  18. ~Base() {}
  19.  
  20. void printInfo() {std::cout << m_classType << std::endl;}
  21.  
  22. template<typename T, typename ... Args>
  23. static typename std::enable_if<std::is_base_of<Base, T>::value, std::unique_ptr<T>>::type create(Args ... args)
  24. {
  25. std::unique_ptr<T> result(new T(args...));
  26. result->initializeImpl();
  27. return result;
  28. }
  29.  
  30. protected:
  31. int m_classType;
  32.  
  33. virtual void initialize()
  34. {
  35. m_classType = BaseClass;
  36. }
  37.  
  38. private:
  39. void initializeImpl()
  40. {
  41. initialize();
  42. }
  43. };
  44.  
  45. class Derived1 : public Base
  46. {
  47. public:
  48. Derived1()
  49. {
  50. ;
  51. }
  52.  
  53. private:
  54. void initialize() {m_classType = Derived1Class;}
  55. };
  56.  
  57. class Derived2 : public Base
  58. {
  59. public:
  60. Derived2()
  61. {
  62. ;
  63. }
  64.  
  65. private:
  66. void initialize() {m_classType = Derived2Class;}
  67. };
  68.  
  69. class Derived3 : public Base
  70. {
  71. public:
  72. Derived3(int a) : m_type(a)
  73. {
  74. ;
  75. }
  76.  
  77. private:
  78. int m_type;
  79.  
  80. void initialize() {m_classType = m_type;}
  81. };
  82.  
  83. class Derived4
  84. {
  85. public:
  86. Derived4(int a) : m_type(a)
  87. {
  88. ;
  89. }
  90.  
  91. private:
  92. int m_type;
  93.  
  94. void initialize() {;}
  95. };
  96.  
  97. int main() {
  98. auto c1 = Base::create<Derived1>();
  99. auto c2 = Base::create<Derived2>();
  100. auto c3 = Base::create<Derived3>(10);
  101. // auto c4 = Base::create<Derived4>(20);
  102.  
  103. c1->printInfo();
  104. c2->printInfo();
  105. c3->printInfo();
  106.  
  107. return 0;
  108. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
1
2
10