此文编写参考狄泰软件学院唐佐林老师的视频课程,如有错误之处,欢迎指正。
一、预备知识
1、模板参数可以是数值型参数(非类型参数)
template
<typename T,int N>
void func()
{
T a[N];//使用模板参数定义局部数组
}
func<double,10>();
2、数值型模板参数的限制
- 变量不能作为模板参数
- 浮点数不能作为模板参数
- 类对象不能作为模板参数
- 。。。。。。
本质:模板参数是在编译阶段被处理的单元,因此,在编译阶段必须准确无误的唯一确定。
3、用最高效的方法求1+2+…N的值
#include<iostream>
using namespace std;
template
<int N>//定义模板,模板参数为数值型
class Sum
{
public:
static const int VALUE=Sum<N-1>::VALUE+N;//定义一个常量VALUE,该常量存入符号表中,切存储在静态存储区
};
template
<>
class Sum<1>
{
public:
static const int VALUE=1;
};
int main()
{
cout<<"Sum<100>::VALUE="<<Sum<100>::VALUE<<endl;
return 0;
}
二、数组类模板
1、普通
//test.cpp main
#include<iostream>
#include"Array.h"
using namespace std;
int main()
{
Array<string,5> array;
for(int i=0;i<array.length();i++)
{
if(i==0)
array[i]+="A";
else
array[i]=array[i-1]+"A";
}
for(int i=0;i<array.length();i++)
{
cout