CPP_template

泛型编程是独立于任何特定类型的方式编写代码。模板是泛型编程的基础,模板使程序员能够快速建立具有类型安全的类库集合和函数集合,它的实现,方便了大规模的软件开发。

模板提供通用类型和通用函数,定义中包含template,和一对尖括号<>,尖括号里面是模板参数。模板参数与普通参数的区别在于,模板参数不仅可以传变量和值,还可以传类型。
模板应放到头文件中。模板本质上就是一种宏定义。

1. 函数模板

template<类型形式参数表> 返回类型 functionName(形式参数表)
{
//函数定义体
}
其中返回类型可以包含基本数据类型,也可以包含类类型。如果是类类型,则需加前缀class。
template <typename T> T abs(T x)
{
return x<0? -x:x;
}
int n=5; double d=-5.5;
cout<<abs(n)<<endl;
cout<<abs(d)<<endl;

// 模板函数
template <class T> T power(T a, int exp)
{
T ans = a;
while(--exp>0){
ans *= a;
}

return (ans);
}

应用时:
函数名 <模块参数> (函数参数)
power<int> (2, 2) = 4;

2. 类模板

template <模板参数表> class 类名
{
类成员声明;
};
在类模板以外定义成员函数
template <模板参数表> 类型名 类名<参数列表>::函数名(参数表)

template <typename T> class Example{};

模板类中的函数都是模板函数。
template <class T> Node<T>::~Node()
{
......
}

原文地址:https://www.cnblogs.com/embedded-linux/p/9613829.html