fork download
  1.  
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <list>
  5.  
  6. using namespace std;
  7.  
  8. // Item
  9. class MyA { };
  10. class MyB { };
  11.  
  12. template <class T>
  13. class MyItem
  14. {
  15. public:
  16. void Print();
  17. };
  18.  
  19. template <>
  20. void MyItem<MyA>::Print()
  21. {
  22. cout << "MyItem - MyA" << endl;
  23. }
  24.  
  25. template <>
  26. void MyItem<MyB>::Print()
  27. {
  28. cout << "MyItem - MyB" << endl;
  29. }
  30.  
  31. // ItemList
  32. class MyItemList
  33. {
  34. public:
  35. template <typename T>
  36. void AddItem(MyItem<T> theItem);
  37.  
  38. void PrintItems();
  39.  
  40. private:
  41. template <typename T>
  42. list<MyItem<T>> & GetTypedList();
  43.  
  44. list<MyItem<MyA>> myAList;
  45. list<MyItem<MyB>> myBList;
  46. };
  47.  
  48. template <typename T>
  49. void MyItemList::AddItem(MyItem<T> theItem)
  50. {
  51. GetTypedList<T>().push_back(theItem);
  52. }
  53.  
  54. template <>
  55. list<MyItem<MyA>> & MyItemList::GetTypedList()
  56. {
  57. return myAList;
  58. }
  59.  
  60. template <>
  61. list<MyItem<MyB>> & MyItemList::GetTypedList()
  62. {
  63. return myBList;
  64. }
  65.  
  66. void MyItemList::PrintItems()
  67. {
  68. // Reihenfolge ist uns mal egal
  69. for_each(myAList.cbegin(), myAList.cend(), [](MyItem<MyA> i)
  70. {
  71. i.Print();
  72. });
  73.  
  74. for_each(myBList.cbegin(), myBList.cend(), [](MyItem<MyB> i)
  75. {
  76. i.Print();
  77. });
  78. }
  79.  
  80. // main
  81. int main(int argc, char * argv[])
  82. {
  83. MyItemList itemList;
  84.  
  85. // itemList soll die Elemente tatsächlich besitzen
  86. {
  87. itemList.AddItem(MyItem<MyA>());
  88. itemList.AddItem(MyItem<MyB>());
  89. }
  90.  
  91. itemList.PrintItems();
  92.  
  93. return 0;
  94. }
  95.  
Success #stdin #stdout 0s 3060KB
stdin
Standard input is empty
stdout
MyItem - MyA
MyItem - MyB