1. 成员模板( member template)
一个类( 无论是普通类还是类模板) 可以包含本身是模板的成员函数。
成员模板不能是虚函数。
1.1 普通( 非模板 ) 类的成员模板
/ / 函数对象类, 对给定指针执行 deleteclass DebugDelete {public:DebugDelete (std:rostream &s = std::cerr ): os (s) {}/ / 与任何函数模板相同, T 的类型由编译器推断template <typename T> void operator ( ) (T *p) const{os « "deleting unique_ptr" « std::endl; delete p;}private:std::ostream &os;}
double* p new double;DebugDelete d; / / 可像 delete 表达式一样使用的对象d (p); / / 调用 DebugDelete::operator ( ) (double* ) , 释放 pint* ip;// 在一个临时 DebugDelete 对象上调用 operator ( ) (int*)DebugDelete ( ) (ip);/ / 销 毁 p 指向的对象//实例化 DebugDelete::operator ( > <int> (int * )unique_ptr<int, DebugDelete> p (new int, DebugDelete ( ) );// 销 毁 sp 指向的对象/ / 实例化 DebugDelete::operator ( ) <string> (string* )unique_ptr<string, DebugDelete> sp (new string, DebugDelete ( ) );/ / DebugDelete 的成员模板实例化样例void DebugDelete::operator ( ) (int *p) const {delete p; }void DebugDelete::operator ( ) (string *p) const {delete p; }
1.2 类模板的成员模板
类模板也可以有成员模板,此时类和成员各自有自己的、独立的模板参数。
template <typename T> class Blob {template <typename It> Blob (It b, It e);//.. .}
与类模板的普通函数成员不同, 成员模板是函数模板。
当我们在类模板外定义一个成员模板时, 必须同时为类模板和成员模板提供模板参数列表。 类模板的参数列表在前, 后跟成员自己的模板参数列表:
//定义一个类模板的成员, 类模板有一个模板类型参数, 命名为 T。// 而成员自身是一个函数模板, 它有一个名为 It 的类型参数。template <typename T>//类的类型参数//构造函数的类型参数template <typename It> Blob<T>::Blob (It b, It e):data (std::make_shared<std::vector<T»(b, e) ) {}
1.3 实例化与成员模板
为了实例化一个类模板的成员模板, 我们必须同时提供类和函数模板的实参。
int ia[] = {0,1,2,3,4,5,6, 7,8,9};vector<long> vi = {0,1,2,3,4,5,6, 7,8,9};list<const char*> w = {"now", "is", "the", "time" };// 实例化 Blob<int>类及其接受两个 int*参数的构造函数Blob<int> al (begin (ia) , end (ia) );// 实 例 化 Blob<int>类的接受两个 vector<long>::iterator 的构造函数Blob<int> a2 (vi.begin ( ), vi.end ( ) );// 实例化Blob<string>及其接受两个list<const char*〉: : iterator 参数的构造函数Blob<string> a3 ( w.begin ( ), w.end ( ) );