C++教程(3) 模板和泛型编程
模板
函数模板
通过 template 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19#include <iostream>
using namespace std;
template <typename T>
int compare(const T &a, const T &b) {
if(a < b) return -1;
if(a > b) return 1;
return 0;
}
int main() {
int a = 1, b = 5;
double c = 2, d = -1;
string e = "A", f = "A";
std::cout << compare(a, b) << std::endl;
std::cout << compare(c, d) << std::endl;
std::cout << compare(e, f) << std::endl;
getchar();
return 0;
}
结果: -1 1 0
模板函数返回值1
2
3
4
5
6template <typename T>
T compare(const T &a, const T &b) {
T temp = b;
....
return temp;
}
多个模板函数参数1
2
3
4template <typename T,typename U>
int compare(const T &a, const U &b) {
....
}
内联模板函数1
2template <typename T>
inline int min(const T &a, const T &b);
类模板
1 | |
Note:T top() const; 表示函数Top()为只读操作,不能对类成员进行修改
默认模板参数1
template <class T=int> class Stack {...}
成员模板
普通类里定义模板函数或模板内部类1
2
3
4
5class Car {
template <typename T> void run(T &);
};
//定义
template<typename T> void Car::run(T & a,){...}
类模板里定义独立的成员模板1
2
3
4
5
6
7template <typename T> class Car {
template <typename U> void run (U a, U b);
};
//定义
template<typename T>
template<typename U>
void Car<T>::run(U a, U b){...}
函数模板显式实参
显示模板实参在调用时由用户指出1
2
3
4
5template <typename T1,typename T2,typename T3>
T3 sum(T1,T2);//T3为显示模板实参
double a = 2.0,b = 3.0;
auto val = sum<int>(a,b);//指定显示模板实参T3为int,T2,T3由a,b推断得出
可变参数模板
1 | |