fork download
  1. #include <algorithm>
  2. #include <cassert>
  3. #include <memory>
  4. #include <vector>
  5.  
  6. struct Getter {
  7. virtual int get() const = 0;
  8. };
  9.  
  10. struct Changer {
  11. virtual void change(int v) = 0;
  12. };
  13.  
  14. struct DataStorage;
  15.  
  16. typedef std::vector<std::unique_ptr<DataStorage> > MList;
  17.  
  18. struct Registrar {
  19. Registrar(MList &mlist) : mlist(mlist) { }
  20. void add(std::unique_ptr<DataStorage>);
  21.  
  22. private:
  23. MList &mlist;
  24. };
  25.  
  26. void Registrar::add(std::unique_ptr<DataStorage> item)
  27. {
  28. mlist.push_back(std::move(item));
  29. }
  30.  
  31. // Plugins can create new instances of this class as needed
  32. struct DataStorage : Getter, Changer {
  33. public:
  34. DataStorage(int v)
  35. : val(v)
  36. {
  37. }
  38.  
  39. virtual int get() const { return val; }
  40. virtual void change(int v) { val = v; }
  41.  
  42. protected:
  43. int val;
  44. };
  45.  
  46. // List of data storage objects templated on which interface
  47. // we want.
  48. template <typename Base>
  49. struct DataStorageList {
  50. struct ItemAccessor {
  51. ItemAccessor(MList &mlist)
  52. : iter(mlist.begin()), end(mlist.end())
  53. {
  54. }
  55.  
  56. // Returns a null pointer if there are no more items
  57. Base *nextPtr()
  58. {
  59. if (iter==end) return 0;
  60. return (*iter++).get();
  61. }
  62.  
  63. private:
  64. MList::iterator iter, end;
  65. };
  66.  
  67. DataStorageList(MList &mlist) : mlist(mlist) { }
  68.  
  69. ItemAccessor itemAccessor() const
  70. {
  71. return ItemAccessor(mlist);
  72. }
  73.  
  74. private:
  75. MList &mlist;
  76. };
  77.  
  78. struct Plugin {
  79. void initialize(Registrar &registrar)
  80. {
  81. // Use registrar to register new data storage objects if needed
  82. registrar.add(std::unique_ptr<DataStorage>(new DataStorage(1)));
  83. }
  84.  
  85. void run(DataStorageList<Getter> getter_list)
  86. {
  87. // Use getter_list if you need access to the data storage objects
  88. // but only as getters.
  89. DataStorageList<Getter>::ItemAccessor
  90. item_accessor = getter_list.itemAccessor();
  91. while (Getter *getter_ptr = item_accessor.nextPtr()) {
  92. // Do something with the getter_ptr
  93. }
  94. }
  95. };
  96.  
  97. int main(int,char**)
  98. {
  99. MList mlist;
  100. Registrar registrar(mlist);
  101. Plugin plugin;
  102. plugin.initialize(registrar);
  103. DataStorageList<Getter> getter_list(mlist);
  104. plugin.run(getter_list);
  105. }
  106.  
Success #stdin #stdout 0s 3024KB
stdin
Standard input is empty
stdout
Standard output is empty