学习的网址:
C++ 模板详解 https://www.runoob.com/w3cnote/c-templates-detail.html
C++模板template用法 https://www.jianshu.com/p/31d7e18372e2
C++中 模板Template的使用 https://www.cnblogs.com/cynchanpin/p/7127897.html
通常有两种形式:函数模板 和 类模板
函数模板
1. 函数模板的经典例子:
#include <iostream>
//swap函数编译不过和系统自带的有冲突,用了swap1
template<typename T> void swap1(T &a, T &b)
{
T tmp{a};
a = b;
b = tmp;
}
int main(int argc, char* argv[])
{
int a = 2;
int b = 3;
swap1(a, b); // 使用函数模板
std::cout << "a=" << a << ", b=" << b << std::endl;
double c = 1.1;
double d = 2.2;
swap(c, d);
std::cout << "c=" << c << ", d=" << d << std::endl;
return 0;
}
函数模板的声明形式为:
//多个形参
template <class 形参名,class 形参名,......> 返回类型 函数名(参数列表)
{
函数体
}
template <class T1,class T2,......> 返回类型 函数名(参数列表)
{
函数体
}
//单个形参
//typename(或class)是声明数据类型參数标识符的关键字
template <typename T> 返回类型 函数名(参数列表)
{
函数体
}
隐式实例化: 可能影响效率,
显式实例化: 在编译期间就会生成实例(增加了编译时间)
类模板
#include <iostream>
using namespace std;
template <class T>
class A
{
public:
T value;
template <class T2>
void Func(T2 t) { cout << t<<endl; } //成员函数模板
//cout 需要加上<<endl;才能显示到终端
//cout cout<<t; 终端没有显示
};
int main()
{
A<int> a;
a.value = 10;
a.value = 5.0; //value =5
a.Func('K'); //成员函数模板Func被实例化
a.Func("hello");
cout<<"hello world"<<endl;
return 0;
}