fork download
  1. #include <memory>
  2. #include <string>
  3. #include <map>
  4.  
  5. template <typename> struct manager;
  6.  
  7. template <typename T>
  8. struct managed_resource
  9. {
  10. typedef std::shared_ptr<manager<T>> manager_ptr;
  11.  
  12. managed_resource(manager_ptr const & parent)
  13. : parent_(parent)
  14. {
  15. }
  16.  
  17. /* ... */
  18.  
  19. manager_ptr parent_;
  20. };
  21.  
  22. template <typename Policy>
  23. struct manager
  24. : Policy
  25. , std::enable_shared_from_this<manager<Policy>>
  26. {
  27. typedef managed_resource<Policy> resource;
  28. typedef std::shared_ptr<resource> resource_ptr;
  29.  
  30. resource_ptr get_resource(std::string const & name)
  31. {
  32. Policy & p = *this;
  33. if(p.find(name))
  34. {
  35. return p.get(name);
  36. }
  37. resource_ptr res = std::make_shared<resource>(this->shared_from_this());
  38. p.store(name, res);
  39. return res;
  40. }
  41. };
  42.  
  43. struct map_policy
  44. {
  45. typedef std::shared_ptr<managed_resource<map_policy>> resource_ptr;
  46. typedef std::map<std::string, resource_ptr> resources;
  47.  
  48. bool find(std::string const & name)
  49. {
  50. resources::iterator res_it = resources_.find(name);
  51. return res_it != resources_.end();
  52. }
  53.  
  54. resource_ptr get(std::string const & name)
  55. {
  56. resources::iterator res_it = resources_.find(name);
  57. return res_it->second;
  58. }
  59.  
  60. void store(std::string const & name, resource_ptr const & res)
  61. {
  62. resources_[name] = res;
  63. }
  64.  
  65. resources resources_;
  66. };
  67.  
  68. typedef manager<map_policy> my_manager;
  69.  
  70. int main()
  71. {
  72. auto m = std::make_shared<my_manager>();
  73. auto res = m->get_resource("test");
  74. return 0;
  75. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Standard output is empty