奇特递归模板模式
来源:互联网 发布:网络给人们带来的好处 编辑:程序博客网 时间:2024/05/05 12:02
有些时候需要对一个类新添加的对象进行计数,这个估计很多人都会,所有工作就是添加静态成员、修改构造函数和析构函数而已。但有时候又会有一些麻烦的事发生,就是想对一个类家族的每一个类都进行单独计数时,难道每个类单独添加这样的工作么,这样的工作量也未免太大了吧?但是采用从基类继承下来的方法又会有另一个问题出现,下面看看代码:
01 //: C05:CountedClass2.cpp
02 // Erroneous attempt to count objects.
03 #include <iostream>
04 using namespace std;
05 class Counted {
06 static int count;
07 public:
08 Counted() { ++count; }
09 Counted(const Counted&) { ++count; }
10 ~Counted() { --count; }
11 static int getCount() { return count; }
12 };
13 int Counted::count = 0;
14 class CountedClass : public Counted {};
15 class CountedClass2 : public Counted {};
16 int main() {
17 CountedClass a;
18 cout << CountedClass::getCount() << endl; // 1
19 CountedClass b;
20 cout << CountedClass::getCount() << endl; // 2
21 CountedClass2 c;
22 cout << CountedClass2::getCount() << endl; // 3 (Error)
23 } ///:~
这种情况下是为派生自Counted所有类进行计数,而不是我们要的对每个派生自Counted单独进行计数,因为派生自Counted的所有类都共享了相同且唯一的静态数据成员。这时要怎么办,难道要自己为每个类都进行重复的工作么?其实一种奇特的模板构造实现了这种方式,如下:
02 #include <iostream>
03 using namespace std;
04 template<class T> class Counted {
05 static int count;
06 public:
07 Counted() { ++count; }
08 Counted(const Counted<T>&) { ++count; }
09 ~Counted() { --count; }
10 static int getCount() { return count; }
11 };
12 template<class T> int Counted<T>::count = 0;
13 // Curious class definitions
14 class CountedClass : public Counted<CountedClass> {};
15 class CountedClass2 : public Counted<CountedClass2> {};
16 int main() {
17 CountedClass a;
18 cout << CountedClass::getCount() << endl; // 1
19 CountedClass b;
20 cout << CountedClass::getCount() << endl; // 2
21 CountedClass2 c;
22 cout << CountedClass2::getCount() << endl; // 1 (!)
23
24 } ///:~
- 奇特递归模板模式
- C++惯用法:奇特的递归模板模式
- templates — C++模板的应用<奇特的递归模板模式>
- templates — C++模板的应用<奇特的递归模板模式>
- 类对象引用计数使用模板实现(奇特的递归模板模式)
- C++惯用法:奇特的递归模板模式(Curiously Recurring Template Pattern,CRTP,Mixin-from-above)
- C++惯用法:奇特的递归模板模式(Curiously Recurring Template Pattern,CRTP,Mixin-from-above)
- C++惯用法:奇特的递归模板模式(Curiously Recurring Template Pattern,CRTP,Mixin-from-above)
- C++惯用法:奇特的递归模板模式(Curiously Recurring Template Pattern,CRTP,Mixin-from-above)
- 递归模板模式
- CRTP 奇异递归模板模式
- 简单递归—奇特的数字系列
- 递归模板实现单例模式
- 递归模板模式--The curiously recurring template pattern
- c++模板递归单例模式进阶版本
- 奇异递归模板模式(Curiously Recurring Template Pattern,CRTP)
- 奇异递归模板模式(CRTP)应用--表达式模板(expression template) 2
- 函数模板递归问题!
- 第一次的笔记
- 杭电分类
- 我的笔记
- [转]最牛MSN签名
- C++之再看笔记
- 奇特递归模板模式
- 弄了一个下午,连个数据库都没连成功,谁能救救我啊!!!
- 一些很好的教程网址
- 新的开始
- 我的实习感悟
- 兼容IE8 代码<meta http-equiv="X-UA-Compatible" content="IE=Emu
- 三个字组成的字:晶、鑫、淼……
- 编程
- 八款开源Android游戏引擎(转载)