1、为什么需要模板
将具有相同逻辑的一段代码提供一份模板,当我们需要处理不同类型的时候,可以通过数据类型当作参数来传递,从而实例化出对应类型的处理版本。


2、模板的定义
也是一种静态多态。

3、模板的分类

4、函数模板


5、函数模板的使用

通常我们把模板的实现放在.h文件中,不放在.cpp文件中,因为编译的时候需要去推导模板函数,这个时候如果放在cpp文件中,则实例化的时候找不到实现。

#include <iostream>
using namespace std;template <typename T>
const T& max(const T& a, const T& b)
{return a < b ? b : a;
}// 编译过后会生成模板函数,但是不可见
//const int& max(const int& a, const int& b)
//{
//    return a < b ? b : a;
//}class Test
{
public:friend bool operator<(const Test& t1, const Test& t2){return true;}
};int main() {cout << ::max(5.5, 6.6) << endl;  // 编译器根据参数自动推导出模板函数cout << ::max('a', 'c') << endl;Test t1;Test t2;::max(t1, t2);return 0;
}6、函数模板特化
当你传入的是指针的类型的话,则比较的是指针的大小,而不是指针指向内容的大小,这样不符合我们预期,所以需要特化。特化表示我们组要给特殊的类型做特殊的操作。

没加特化前:
template <typename T>
const T& max(const T& a, const T& b)
{return a < b ? b : a;
}class Test
{
public:friend bool operator<(const Test& t1, const Test& t2){return true;}
};int main() {const char* str1 = "zzz";const char* str2 = "aaa";cout << ::max(str1, str2) << endl;return 0;
}// 输出
aaa加上特化后:
#include <iostream>
using namespace std;#include <cstring>template <typename T>
const T& max(const T& a, const T& b)
{return a < b ? b : a;
}// 函数模板特化
template <>
const char* const& max(const char* const& a, const char* const& b)
{return strcmp(a, b) < 0 ? b : a;
}class Test
{
public:friend bool operator<(const Test& t1, const Test& t2){return true;}
};int main() {const char* str1 = "zzz";const char* str2 = "aaa";cout << ::max(str1, str2) << endl;return 0;
}// 输出
zzz7、重载函数模板

模板特化还算是模板函数,但是非模板函数重载,已经不算模板函数。
#include <iostream>
using namespace std;#include <cstring>template <typename T>
const T& max(const T& a, const T& b)
{return a < b ? b : a;
}// 函数模板重载
template <typename T>
const T& max(const T& a, const T& b, const T& c)
{return ::max(a, b) < c ? c : ::max(a, b);
}// 非模板函数重载
const int& max(const int& a, const int& b)
{cout << "non template" << endl;return a < b ? b : a;
}// 函数模板特化
template <>
const char* const& max(const char* const& a, const char* const& b)
{return strcmp(a, b) < 0 ? b : a;
}int main() {cout << ::max(1, 5, 3) << endl;cout << ::max('a', 100) << endl;  // 非函数模板中将字符隐式转化成整型cout << ::max(94, 100) << endl;cout << ::max<>(94, 100) << endl;  // 自动推导max(const int& a, const int& b)cout << ::max<int>(97, 100) << endl;  // 显示指定模板函数(加上<>表示要使用模板函数)cout << ::max<int>('a', 100) << endl;return 0;
}// 输出
5
non template
100
non template
100
100
100
100