fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <list>
  4.  
  5. class Base {
  6. friend class BaseWrapper;
  7. friend std::ostream & operator << (std::ostream &os, const Base &b) {
  8. b.print(os);
  9. return os;
  10. }
  11. virtual void print (std::ostream &os) const = 0;
  12. virtual Base * clone () const = 0;
  13. protected:
  14. template <typename T> static Base * clone_impl (const T &t) {
  15. return new T(t);
  16. }
  17. public:
  18. virtual ~Base () {}
  19. };
  20.  
  21. class Derived1 : public Base {
  22. std::string s;
  23. void print (std::ostream &os) const { os << s; }
  24. Base * clone () const { return clone_impl(*this); }
  25. public:
  26. Derived1 () : s("D1") {}
  27. };
  28.  
  29. class Derived2 : public Base {
  30. int x;
  31. std::string s;
  32. double y;
  33. void print (std::ostream &os) const { os << (x + y) << ":" << s; }
  34. Base * clone () const { return clone_impl(*this); }
  35. public:
  36. Derived2 () : x(3), s("D2"), y(.14159) {}
  37. };
  38.  
  39. class Derived3 : public Base {
  40. std::string s;
  41. void print (std::ostream &os) const { os << s; }
  42. Base * clone () const { return clone_impl(*this); }
  43. public:
  44. Derived3 () : s("D3") {}
  45. };
  46.  
  47. class BaseWrapper : public Base {
  48. std::unique_ptr<Base> ptr;
  49. void print (std::ostream &os) const { ptr->print(os); }
  50. Base * clone () const { return ptr->clone(); }
  51. public:
  52. BaseWrapper (const Base &b) : ptr(b.clone()) {}
  53. BaseWrapper (BaseWrapper &&b) { ptr.swap(b.ptr); }
  54. };
  55.  
  56. typedef std::list<BaseWrapper> any_list;
  57.  
  58. int main ()
  59. {
  60. any_list l;
  61. l.push_back(Derived1());
  62. l.push_back(Derived2());
  63. l.push_back(Derived3());
  64.  
  65. for (const auto &x : l) {
  66. std::cout << " " << x;
  67. }
  68. std::cout << std::endl;
  69. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
 D1 3.14159:D2 D3