模板作为一个框架,通过传入的参数,来具体实例化想要的东西。
1.模板定义是用template关键字开头的,后跟<>,<>里面叫模板参数列表(模板实参),如果模板参数列表中有多个参数使用逗号隔开。
2.<>里面至少要有一个模板参数,模板参数前有typename/class关键字。
3.模板参数列表里的参数,表示在函数定义中用到的(类型)或(值)。
4.我们使用时有时候需要指定具体实参;有时候由系统推导出。
template<typename T>
T funcadd(T a, T b)
{T addhe = a + b;return addhe;
}template<class T>
T funcadd(T a, T b)
{T addhe = a + b;return addhe;
}
5.传入非类型参数实参,必须为常量表达式。
#include <iostream>
using namespace std;template<int a, int b>
int funcadd()
{int addhe = a + b;return addhe;
}int main()
{//传入的必须为常量表达式cout << funcadd<10,20>() << endl;return 0;
}
6.混合模板参数列表使用
#include <iostream>
using namespace std;template<typename T,int a, int b>
int funcadd(T c)
{int addhe = int(c) + a + b;return addhe;
}int main()
{cout << funcadd<int,10,20>(30) << endl;return 0;
}