函数模板概念
函数模板可以表示很多个函数,函数模板与类型无关,在使用时被参数化,根据实参类型产生函数的特定类型版本
函数模板格式
template<typename T1,typename T2, ..... typename Tn >
返回值类型 函数名(参数列表){}
用不同类型的参数使用函数模板时,称为函数模板的实例化
1. 隐式实例化:让编译器根据实参推演模板参数的实际类型
2. 显式实例化:在函数名后的<>中指定模板参数的实际类型
//自定义类型 struct A{ A(int a) :_a(a) {} int _a = 1; }; //函数模板 //T: 模板参数 template<typename T> void Swap(T& a, T& b){ T temp = a; a = b; b = temp; } void test(){ int a = 1, b = 2; char d = 'm', e = 'n'; double f = 1.2, g = 2.5; A a1(10); A a2(20);
//隐式实例化 Swap(a, b); Swap(d, e); Swap(f, g); Swap(a1, a2); cout << a <<' '<< b <<" "<< d <<' '<< e <<" "<< f <<' '<< g <<endl; }
#include<iostream> using namespace std; //typename经常可以使用class代替,但不能使用struct代替 template<typename T> T add(T a, T b){ return a + b; } template<class T1,class T2,class T3> void print(const T1& a, const T2& b, const T3& c){ cout << a << ' ' << b << ' ' << c << endl; } void test(){ int a = 1, b = 2; char d = 'm', e = 'n'; double f = 1.2, g = 2.5; add(a, b); //add(a, e);类型不匹配 //强制类型转换 add(a, (int)e); //编译器不能进行类型推导的时候, 使用显式实例化 //显式实例化 add<int>(a, e); print(a, b, e); print(a, d, f); } int main(){ test(); system("pause"); return 0; }
类模板:
#include<iostream> using namespace std; template < class T > class seqList{ public: seqList(int n) :_data(new T[n]) , _size(0) , _capacity(n) {} T seqListAt(size_t pos); private: T* _data; size_t _size; size_t _capacity; }; //类外定义函数:需要加泛型声明 template<class T> T seqList::seqListAt(size_t pos){ return _data[pos]; } void test(){ //seqList sq;不能隐式实例化 //显式实例化,真正的类型 --> 类名<模板参数类型> seqList<int> sq(10); seqList<double> sq2(10); }