fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. #include <random>
  5. #include <array>
  6.  
  7.  
  8. struct a
  9. {
  10. virtual ~a() = default;
  11. };
  12.  
  13. struct b : public a {};
  14. struct c : public a {};
  15.  
  16.  
  17. using pointer_type = std::unique_ptr<a>;
  18. using vector_type = std::vector<pointer_type>;
  19.  
  20. pointer_type random_class()
  21. {
  22. static std::mt19937 gen((std::random_device())());
  23. std::uniform_int_distribution<unsigned> dist(0, 2);
  24.  
  25. switch (dist(gen))
  26. {
  27. case 0: return pointer_type(new a);
  28. case 1: return pointer_type(new b);
  29. case 2: return pointer_type(new c);
  30. }
  31. }
  32.  
  33. const char* identity(const a* object)
  34. {
  35. if (const c* o = dynamic_cast<const c*>(object))
  36. return "c";
  37.  
  38. if (const b* o = dynamic_cast<const b*>(object))
  39. return "b";
  40.  
  41. return "a";
  42. }
  43.  
  44. template<typename iter_type>
  45. void display(iter_type beg, iter_type end)
  46. {
  47. std::cout << "{ ";
  48. while (beg != end)
  49. std::cout << identity((beg++)->get()) << ' ';
  50. std::cout << "}\n";
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56. vector_type v;
  57. for (unsigned i = 0; i < 10; ++i)
  58. v.emplace_back(random_class());
  59.  
  60. display(v.begin(), v.end());
  61. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
{ c c a b c a b a a c }