【问题标题】:Extract common class behaviour in a template提取模板中的常见类行为
【发布时间】:2011-11-30 17:38:38
【问题描述】:

我观察到在我的程序中,我需要让几个类使用以下通用模式。它背后的想法是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(管理相同类型资源的管理器类)是一个朋友类(因此它可以创建/销毁实例)

【问题讨论】:

  • 什么常见的行为? resource_imp 的?
  • resource_implresource_mgr
  • resource 是如何发挥作用的?
  • resource 只是我使用的 typedef。我将从问题中删除它以使事情更清楚。
  • 您能否展示几个将使用此共享功能的对象的示例或伪代码,以及说明您希望如何使用它的伪代码?

标签: c++ templates generics


【解决方案1】:

首先添加接口:

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

然后把resource_impl改成模板:

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 类。

【讨论】:

  • 我可以在编译时强制,对于模板resource_mgr,typename T 是resource_impl 模板(即不允许resource_mgr&lt;int&gt;)吗?
猜你喜欢
  • 2015-04-25
  • 1970-01-01
  • 2016-07-20
  • 2010-09-16
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
相关资源
最近更新 更多