fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <utility>
  4. #include <vector>
  5.  
  6. struct Shape
  7. {
  8. virtual void draw() = 0;
  9. };
  10.  
  11. template<typename T>
  12. struct ShapeAdapter:
  13. Shape
  14. {
  15. template<typename... Args>
  16. ShapeAdapter(Args&&... args):
  17. data(std::forward<Args>(args)...)
  18. {}
  19.  
  20. virtual void draw() override
  21. {
  22. data.draw();
  23. }
  24.  
  25. T data;
  26. };
  27.  
  28. struct ShapeCollection
  29. {
  30. template<typename T, typename... Args>
  31. void add(Args&&... args)
  32. {
  33. auto ptr = new ShapeAdapter<T>{ std::forward<Args>(args)... };
  34. shapes.emplace_back(ptr);
  35. }
  36.  
  37. void draw()
  38. {
  39. for (auto&& shape: shapes)
  40. {
  41. shape->draw();
  42. }
  43. }
  44.  
  45. std::vector<std::unique_ptr<Shape>> shapes;
  46. };
  47.  
  48.  
  49. struct Circle
  50. {
  51. Circle(int x, int y, int radius) {}
  52.  
  53. void draw()
  54. {
  55. std::cout << "draw circle\n";
  56. }
  57. };
  58.  
  59. struct Square
  60. {
  61. Square(int x, int y, int height, int length) {}
  62.  
  63. void draw()
  64. {
  65. std::cout << "draw square\n";
  66. }
  67. };
  68.  
  69.  
  70. int main()
  71. {
  72. ShapeCollection collection;
  73.  
  74. collection.add<Circle>(2, 3, 5);
  75. collection.add<Square>(1, 2, 8, 9);
  76.  
  77. collection.draw();
  78. }
  79.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
draw circle
draw square