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