Retrieving regular class behavior in a template

I noticed that in my program I needed to make several classes using the following general template. The idea behind this is that resource_mgr maintains a list of pointers counting references to resource objects and exclusively controls their lifetime. Clients cannot create or delete resource instances, but they can request them from resource_mgr .

 class resource_impl { public: // ... private: resource_impl(...); ~resource_impl(); // ... friend class resource_mgr; } class resource_mgr { public: // ... shared_ptr<resource_impl> new_resource(...); private: std::vector<shared_ptr<resource_impl> > resources_; static void delete_resource(resource* p); // for shared_ptr } 

How can I (or can?) Define a pattern to capture this common behavior? The following shows how to use this template:

 class texture_data { // texture-specific stuff } typedef resource_impl<texture_data> texture_impl; // this makes texture_impl have private *tors and friend resource_mgr<texture_impl> typedef resource_mgr<texture_impl> texture_mgr; //... texture_mgr tmgr; shared_ptr<texture_impl> texture = tmgr.new_resource(...); 

Update: Different instances of resource_impl should have common properties:

  • They have private constructors and a destructor
  • Their β€œlinked” resource_mgr (the manager class that manages the same type of resource) is a friend class (so it can create / destroy instances).
+4
source share
1 answer

First add the interface:

 class resource_interface { public: virtual ~resource_interface() = 0; virtual void foo() = 0; }; 

Then change the impl_resource to the template:

 template< typename T > class resource_impl : public T { public: // ... private: resource_impl(...); ~resource_impl(); // ... friend template< typename > class resource_mgr; } 

Then change resource_mgr to a template:

 template< typename T > class resource_mgr { public: // ... shared_ptr<T> new_resource(...); private: std::vector<shared_ptr<T> > resources_; static void delete_resource(T* p); // for shared_ptr } 

And you should have very common classes resource_impl and resource_mgr.

+4
source

Source: https://habr.com/ru/post/1383939/


All Articles