fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4. #include <memory>
  5. #include <random>
  6.  
  7. struct Base
  8. {
  9. virtual void print() const = 0;
  10. virtual ~Base() {}
  11. };
  12.  
  13.  
  14. struct D1 : public Base { void print() const { std::cout << "D1\n"; } };
  15. struct D2 : public Base { void print() const { std::cout << "D2\n"; } };
  16. struct D3 : public Base { void print() const { std::cout << "D3\n"; } };
  17. struct D4 : public Base { void print() const { std::cout << "D4\n"; } };
  18. struct D5 : public Base { void print() const { std::cout << "D5\n"; } };
  19.  
  20.  
  21. template <typename T>
  22. T* new_class()
  23. {
  24. return new T;
  25. }
  26.  
  27. typedef std::function<Base*()> creationFunction;
  28.  
  29. enum class_type { eD1, eD2, eD3, eD4, eD5 };
  30.  
  31. creationFunction create [] =
  32. {
  33. new_class<D1>,
  34. new_class<D2>,
  35. new_class<D3>,
  36. new_class<D4>,
  37. new_class<D5>
  38. };
  39.  
  40. Base* getClass(class_type type)
  41. {
  42. return create[type]();
  43. }
  44.  
  45. int main()
  46. {
  47. std::mt19937 engine( (std::random_device())() );
  48. std::uniform_int_distribution<unsigned> ct(eD1, eD5);
  49.  
  50. auto rand_class = [&]() { return static_cast<class_type>(ct(engine)); };
  51.  
  52. std::vector<std::unique_ptr<Base>> container;
  53. for (unsigned i = 0; i < 20; ++i)
  54. container.emplace_back(getClass(rand_class()));
  55.  
  56. for (auto & element : container)
  57. element->print();
  58. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
D5
D5
D5
D3
D2
D1
D5
D1
D3
D2
D5
D3
D1
D3
D5
D2
D5
D1
D3
D5