主要用于:不同的数据类型,相同的实现方法,可以用template封装成一个API。
实例:
class Iprint
{
public:
virtual void process(int value) =0;
virtual void process(double value) =0;
virtual ~Iprint(){}
};
class Print : public Iprint
{
public:
Print()
{
cout<<"this is Print() construct"<
void PrintArray(T value);
};
template void Print:: PrintArray(T value)
{
cout<<"PrintArray value:"<process(10);
p->process(20.0);
return 0;
}
二,泛化类
主要用于:不同的类,相同的成员函数/成员变量等,可以用template封装成一个对象。
有些情况和工厂模式类似。
实例:
template三,常见的问题 1,Missing template arguments before '.' tokenclass Print { public: Print() { cout<<"this is Print() construct"< print1; print1.printType(); cout<<"***************************************"< print2; print2.printType(); return 0; }
原因:若类里包含template模板,该类实例时,不清楚对应的T是什么类型。
方案一:实例化时时指定类型,e.g:A
方案一:可以用虚基类的方式,在派生类的方法里使用template
原因:T没有声明
方案:在定义和声明时都加:template
"typename"是一个C++程序设计语言中的关键字。相当用于泛型编程时是另一术语"class"的同义词。这个关键字用于指出模板声明(或定义)中的依赖的名称(dependent names)是类型名,而非变量名。
很多情况下typename和class用法一样
个人建议:typename用于基本类型,class用于class类型



