I observed that in my program I needed to make several classes use the following common pattern. The idea behind it is that resource_mgr maintains a list of reference-counted pointers to resource objects, and exclusively controls their lifetime. Clients may not create or delete resource instances, but may 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 I?) define a template to capture this common behavior?
The following illustrates how this template might be used:
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: Various instantiations of resource_impl should all have in common the following properties:
- They have private constructors and destructor
- Their “associated”
resource_mgr(the manager class that manages the same type of resource) is a friend class (so it can create/destroy instances)
First add the interface :
Then change the resource_impl into template :
Then change resource_mgr into template:
And you should have very generic resource_impl and resource_mgr classes.