定义、实例化函数模板:

对于函数体完全相同,唯一差异就是参数类型的情况,我们可以定义一个通用的函数模板,而非为每个类型都定义一个新函数:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 template <typename T>//模板参数列表
 6 int compare(const T &v1, const T &v2) {
 7     if(v1 < v2) return -1;
 8     if(v2 < v1) return 1;
 9     return 0;
10 }
11 
12 int main(void) {
13     cout << compare(1, 0) << endl;//T为int
14     cout << compare(vector<int>{1, 2, 3}, vector<int>{2, 3, 4}) << endl;//T为vector<int>
15 
16     return 0;
17 }
View Code

相关文章: