提取模板中常见的类行为
Extract common class behaviour in a template
我注意到,在我的程序中,我需要让几个类使用以下常见模式。其背后的思想是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类
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么istream不支持右值提取
- 如何设置一个范围来提取我想要获得的信息
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 视觉工作室项目.提取源文件夹名称
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 从 std::vector<无符号字符>切片中提取 int?
- 在C++中使用重载提取运算符时出现问题
- C++如何在向量中查找最常见的元素
- 在 Qt(C++) 中使用 QProcess 解压缩 - 提取目录问题
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 无法从 std::string 中提取C++ Unicode 符号
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何从适合一定范围的数字中提取数字?
- 提取模板中常见的类行为
- 用C++程序提取两个句子,找出常见的字母