fork download
  1. /*
  2. (c) 2013 +++ Filip Stoklas, aka FipS, http://w...content-available-to-author-only...S.com +++
  3. THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE
  4. ARTICLE URL: http://f...content-available-to-author-only...s.com/viewtopic.php?f=3&t=1194
  5. */
  6.  
  7. #include <iostream>
  8. #include <vector>
  9. #include <memory>
  10. #include <utility>
  11.  
  12. struct dbgVectorPairInt : std::vector<std::pair<int,int>>
  13. {
  14. dbgVectorPairInt() { std::cout << "dbgVectorPairInt::dbgVectorPairInt()" << std::endl; }
  15.  
  16. dbgVectorPairInt(dbgVectorPairInt const&) { std::cout << "dbgVectorPairInt::dbgVectorPairInt(const&)" << std::endl; }
  17.  
  18. dbgVectorPairInt(dbgVectorPairInt &&) { std::cout << "dbgVectorPairInt::dbgVectorPairInt(&&)" << std::endl; }
  19.  
  20. ~dbgVectorPairInt() { std::cout << "dbgVectorPairInt::~dbgVectorPairInt()" << std::endl; }
  21. };
  22.  
  23. struct Circle
  24. {
  25. void draw(std::ostream &out) { out << "Circle::draw()\n"; }
  26. };
  27.  
  28. struct Square
  29. {
  30. void draw(std::ostream &out) { out << "Square::draw()\n"; }
  31. };
  32.  
  33. struct Polygon
  34. {
  35. void draw(std::ostream &out) { out << "Polygon::draw()\n"; }
  36. dbgVectorPairInt vertices;
  37. };
  38.  
  39. struct List
  40. {
  41. template <typename Shape_T>
  42. void push(Shape_T shape)
  43. {
  44. _shapes.emplace_back(If_ptr(new Slot<Shape_T>(shape)));
  45. }
  46.  
  47. void draw(std::ostream &out)
  48. {
  49. for(auto &shape : _shapes)
  50. {
  51. shape->draw(out);
  52. }
  53. }
  54.  
  55. private:
  56.  
  57. struct If
  58. {
  59. virtual void draw(std::ostream &out) = 0;
  60. };
  61.  
  62. template <typename Shape_T>
  63. struct Slot : public If
  64. {
  65. virtual void draw(std::ostream &out) { shape.draw(out); }
  66.  
  67. Slot(Shape_T shape) : shape(shape) {}
  68. Shape_T shape;
  69. };
  70.  
  71. typedef std::unique_ptr<If> If_ptr;
  72. std::vector<If_ptr> _shapes;
  73. };
  74.  
  75. int main()
  76. {
  77. Square s;
  78. Circle c;
  79. List l;
  80.  
  81. Polygon p;
  82.  
  83. l.push(s);
  84. l.push(c);
  85. l.push(c);
  86. l.push(c);
  87. l.push(p);
  88.  
  89. l.draw(std::cout);
  90.  
  91. return 0;
  92. }
  93.  
  94. // Compiled under Visual C++ 2012, output:
  95. // Square::draw()
  96. // Circle::draw()
  97. // Circle::draw()
  98. // Circle::draw()
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
dbgVectorPairInt::dbgVectorPairInt()
dbgVectorPairInt::dbgVectorPairInt(const&)
dbgVectorPairInt::dbgVectorPairInt(const&)
dbgVectorPairInt::dbgVectorPairInt(const&)
dbgVectorPairInt::~dbgVectorPairInt()
dbgVectorPairInt::~dbgVectorPairInt()
Square::draw()
Circle::draw()
Circle::draw()
Circle::draw()
Polygon::draw()
dbgVectorPairInt::~dbgVectorPairInt()