1.泛型编程:编写与类型无关的通用代码,是代码复用的一种手段。模板是泛型编程的基础
2.函数模板的格式
template<typename T1,typename T2,…,typename Tn>
返回类型 函数名(参数列表)
{
//函数体
}
3.template<class T1,class T2,…,class Tn>
template<class T1,class T2,…,class Tn>
class 类模板名
{
//类内成员声明
};
4.使用模板时,编译器一般不会进行类型转换操作
以下代码将不能通过编译:
T Add(const T& x, const T& y)
{return x + y;
}
int main()
{int a = 10;double b = 1.1;int c = Add(a, b);return 0;
}
因为在编译期间,编译器根据实参推演模板参数的实际类型时,根据实参a将T推演为int,根据实参b将T推演为double,但是模板参数列表中只有一个T,编译器无法确定此处应该将T确定为int还是double。
5.类模板中的成员函数若是放在类外定义时,需要加模板参数列表
template<class T>
class Date
{
public:void Print();
private:T _year;T _month;T _day;
};
//类模板中的成员函数在类外定义,需要加模板参数列表
template<class T>
void Score<T>::Print()
{cout << _year << "-" << _month << "-"<< _day << endl;
}