gpt4 book ai didi

c++ - 在模板中提取常见的类行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:33 28 4
gpt4 key购买 nike

我发现在我的程序中我需要让几个类使用以下通用模式。其背后的想法是 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 的各种实例都应具有以下共同属性:

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

最佳答案

首先添加接口(interface):

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

关于c++ - 在模板中提取常见的类行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8330392/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com