fork download
  1. #include <list>
  2. #include <memory>
  3. #include <functional>
  4. #include <iostream>
  5.  
  6. template<typename TObject, typename... CtorArgs>
  7. class GenericPool {
  8. public:
  9. typedef std::shared_ptr<TObject> TObjectPtr;
  10.  
  11. explicit GenericPool(CtorArgs... args)
  12. {
  13. m_creator = [=]() { return std::make_shared<TObject>(args...); };
  14. }
  15.  
  16. ~GenericPool()
  17. {
  18. }
  19.  
  20. TObjectPtr getObject()
  21. {
  22. if (!m_availables.empty()) {
  23. auto pooled = m_availables.front();
  24. m_availables.pop_front();
  25. return pooled;
  26. }
  27.  
  28. m_availables.push_back(m_creator());
  29. return m_availables.back();
  30. }
  31.  
  32. void release(TObjectPtr &objPtr)
  33. {
  34. m_availables.push_back(objPtr);
  35. m_inUse.remove(objPtr);
  36. objPtr.reset();
  37. }
  38.  
  39. private:
  40. std::function<TObjectPtr()> m_creator;
  41.  
  42. std::list<TObjectPtr> m_availables;
  43. std::list<TObjectPtr> m_inUse;
  44. };
  45.  
  46. struct YobaBase {
  47. YobaBase(int num, char sym) : m_num(num), m_sym(sym) {}
  48. virtual ~YobaBase() {}
  49.  
  50. int m_num;
  51. char m_sym;
  52. };
  53.  
  54. struct YobaDerived : YobaBase {
  55. YobaDerived(int num, char sym, float fnum) : YobaBase(num, sym), m_fnum(fnum) {}
  56.  
  57. float m_fnum;
  58. };
  59.  
  60. int main()
  61. {
  62. typedef GenericPool<YobaBase, int, char> YobaBasePool;
  63. typedef GenericPool<YobaDerived, int, char, float> YobaDerivedPool;
  64.  
  65. YobaBasePool ybPool(0, 'a');
  66. YobaDerivedPool ydPool(5, 'b', 0.0f);
  67.  
  68. auto yb = ybPool.getObject();
  69. auto yd = ydPool.getObject();
  70.  
  71. std::cout << "Yoba base (num = " << yb->m_num << ", sym = " << yb->m_sym << ")" << std::endl;
  72. std::cout << "Yoba derived (num = " << yd->m_num << ", sym = "
  73. << yd->m_sym << ", fnum = " << yd->m_fnum << ")" << std::endl;
  74.  
  75. ybPool.release(yb);
  76. ydPool.release(yd);
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0s 3236KB
stdin
Standard input is empty
stdout
Yoba base (num = 0, sym = a)
Yoba derived (num = 5, sym = b, fnum = 0)