C++中的模版總體可以分為兩大類:模版函數(shù)、模版類。本篇文章先寫(xiě)模版函數(shù),接下來(lái)會(huì)介紹模版類。
定義:模版函數(shù)是通用的函數(shù)描述,也就是說(shuō)它們使用通用類型來(lái)定義,其中的通用類型可用具體類型替換。
代碼實(shí)例:
#include <iostream>//模版函數(shù)的聲明template<typename T>void Swap(T& a,T& b);int main() { int i = 10; int j = 20; std::cout<<"i=" << i << "," << "j=" <<j; Swap(i,j);//生成 void Swap(int &,int&); std::cout<<"i=" << i << "," << "j=" <<j; double x = 11.5; double y = 19.5; std::cout<<"x=" << x << "," << "y=" <<y; Swap(x,y);//編譯器生成 void Swap(double &,double&); std::cout<<"x=" << x << "," << "y=" <<y; return 0; }//模版函數(shù)的定義template<typename T>void Swap(T& a,T& b) { T temp; temp = a; a = b; b = temp; }
網(wǎng)友評(píng)論