参考链接:1.cplusplus
c++ 的template(模板)分为function templates和class templates,模板是能够操作通用类型的一种方法,它能用同样的代码自适应多种类型实现同样的功能,从而实现代码重用。而这是通过使用模板参数 实现的,即将类型也当作参数。
- 函数模板声明:
/***两种使用方式没有区别***/
template <class identifier> function_declaration
template <typename identifier> fucntion_declaration
- 函数模板例子:
#include <iostream>
using namespace std;
//OR: template <typename T> T getMax(T a, T b){...}
template <class T>
T getMax(T a, T b){
return (a > b) ? a : b;
}
int main(){
cout << getMax<int>(5, 6) << endl;
system("pause");
return 0;
}
- 类模板语法:
// 定义
template <class T>
class MyClass{
T par;
public:
T my_func();
int our_func();
}
// 成员函数定义
template <class T> //都要有template <class T> 开头
int MyClass<T>::our_func(){...} //这里不要忘记类后面的<T>
类模板例子:
#include <iostream> using namespace std; template <typename T> class MyPair{ T a, b; public: MyPair(T _a, T _b){ a = _a; b = _b; } T get_max(); }; template <typename T> T MyPair<T>::get_max(){ return a > b ? a : b; } int main(){ MyPair<int> age(21, 23); cout << age.get_max() << endl; system("pause"); return 0; }