1、定義函數模板:
template<typename T>
inline T const& Max(T const& a, T const& b){
return a < b ? b : a;
}
解釋:template表明了這是一個函數模板,<>指定了模板參數區域,typename表明了後面的參數是一個類型名, T是模板參數,它可以用來指定所有的類型,a和b是調用參數,位於模板函數名稱後面,在一對()內進行聲明。這裏typename可以用class來取代,但最好使用typename。
2、調用函數模板
#include<iostream>
#include<string>
using namespace std;
template<typename T>
inline T const& Max(T const& a, T const& b){
return a < b ? b : a;
}
int main(){
cout << Max(5, 8) << endl;
cout << Max(3.4, -6.5) << endl;
string str1 = "math";
string str2 = "mathmatics";
cout << Max(str1, str2) << endl;
system("pause");
return 0;
}
調用函數模板時,模板被編譯兩次:
第一次:實例化之前,檢查模版代碼本身,查看語法是否正確。
第二次:在實例化期間,檢查模版代碼,查看是否所有的調用都有效。
3、重載函數模板
函數模版也可以進行重載,一個非模版函數可以和一個同名的函數模版同時存在,調用的優先級是非模板函數的優先級高。<>符號顯式指定一個空的模板實參列表,告訴編譯器只有模板才能匹配這個調用,而且所有的模板參數都應該根據調用實參演繹出來。函數的所有重載版本的聲明都應該位於該函數被調用的位置之前。
例子說明:
#include<iostream>
#include<string>
using namespace std;
inline int const& Max(int const& a, int const& b){
cout << "調用(1):";
return a < b ? b : a;
}//(1)
template<typename T>
inline T const& Max(T const& a, T const& b){
cout << "調用(2):";
return a < b ? b : a;
}//(2)
template<typename T>
inline T const& Max(T const& a, T const& b,T const& c){
cout << "調用(3):";
return Max(Max(a, b), c);
}//(3)
int main(){
cout << Max(7, 45, 44) << endl;//調用(3)
cout << Max(7.2, 5.7) << endl;//調用(2),Max<double>
cout << Max<>(4, 5) << endl;//調用(2),<>符號顯式指定一個空的模板實參列表,告訴編譯器只有模板才能匹配這個調用
cout << Max(4, 5) << endl;//調用(1)
system("pause");
return 0;
}