一、概念引入
什么叫递归模板模式呢?简单的来说就是:派生类将本身作为模板参数传递给基类
//传递派生类类型
template <typename Derived>
class CuriousBase {
....
};
template <typename T>
class CuriousTemplate : public CuriousBase<CuriousTemplate<T> >{
....
};
//传递派生类本身:双重模板参数的使用
template <template<typename> class Derived>
class MoreCuriousBase {
....
};
template <typename T>
class MoreCurious : public MoreCuriousBase <MoreCurious > {
...
};
二、举例
#include <iostream>
#include<string>
#include<stddef.h>
using namespace std;
//统计某类的对象个数的模板基类
template <typename CountedType>
class ObjectCounter{
protected:
ObjectCounter(){
++ObjectCounter<CountedType>::count;
}
ObjectCounter(const ObjectCounter<CountedType> &){
++ObjectCounter<CountedType>::count;
}
~ObjectCounter(){
--ObjectCounter<CountedType>::count;
}
public:
static size_t live(){
return ObjectCounter<CountedType>::count;
}
private:
static size_t count;
};
template <typename CountedType>
size_t ObjectCounter<CountedType>::count =0;
//结束
//使用模板基类
template <typename CharT>
class MyString : public ObjectCounter<MyString<CharT> >{
....
};
int main(int argc, char *argv[]){
MyString<char> s1,s2;
MyString<wchar_t> ws;
cout<<"numbers of MyString<char>: "<< MyString<char>::live()<<endl;
cout<<"numbers of MyString<wchar_t>: "<< ws.live()<<endl;
return 0;
}