fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. using namespace std;
  5.  
  6. // demo class
  7. class Item {
  8. int i;
  9. public:
  10. Item(int v=0) : i(v) {}
  11. friend ostream& operator<< (ostream& os, const Item &item);
  12. };
  13. ostream& operator<< (ostream& os, const Item &item) {
  14. return (os << item.i);
  15. }
  16.  
  17. template <template <typename...> class C, class T>
  18. class Adder {
  19. public:
  20. void operator() (C<T>& a, const T& element);
  21. };
  22.  
  23. template <class T>
  24. class Adder<vector, T> {
  25. public:
  26. void operator() (vector<T>& a, const T& element) {
  27. a.push_back(element);
  28. }
  29. };
  30.  
  31. template <class T>
  32. class Adder<list, T> {
  33. public:
  34. void operator() (list<T>& a, const T& element) {
  35. a.push_front(element);
  36. }
  37. };
  38.  
  39. template <template <typename...> class C, class T>
  40. class SmartContainer {
  41. C<T> mycontainer;
  42. Adder<C,T> a;
  43. public:
  44. void add (const T& element) { a(mycontainer, element); }
  45. int get_number_of_elements() { return mycontainer.size(); }
  46. void print() { for (auto &x:mycontainer)
  47. cout << x<<endl;
  48. cout<<endl; }
  49. };
  50.  
  51.  
  52. int main() {
  53. Item item1(10), item2(20);
  54.  
  55. SmartContainer<vector, Item> c1;
  56. c1.add(item1);
  57. c1.add(item2);
  58. cout<< "Size: "<<c1.get_number_of_elements()<<endl;
  59. c1.print();
  60.  
  61. SmartContainer<list, Item> c2;
  62. c2.add(item1);
  63. c2.add(item2);
  64. cout<< "Size: "<<c2.get_number_of_elements()<<endl;
  65. c2.print();
  66.  
  67. return 0;
  68. }
  69.  
  70.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Size: 2
10
20

Size: 2
20
10