提取模板中常见的类行为

Extract common class behaviour in a template

本文关键字:常见 提取      更新时间:2023-10-16

我注意到,在我的程序中,我需要让几个类使用以下常见模式。其背后的思想是resource_mgr维护一个指向resource对象的引用计数指针列表,并独占地控制它们的生命周期。客户端不能创建或删除resource实例,但可以从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
}

我如何定义一个模板来捕获这种常见的行为?下面演示了如何使用这个模板:

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(...);

更新: resource_impl的各种实例应该都有以下共同的属性:

  • 它们有私有构造函数和析构函数
  • 它们的"关联"resource_mgr(管理相同类型资源的管理器类)是一个朋友类(因此它可以创建/销毁实例)

首先添加接口:

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

然后将resource_impl改为template:

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

然后将resource_mgr改为模板:

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
}

你应该有非常通用的resource_impl和resource_mgr类