#include <iostream>
#include <string>
using namespace std;
template <class T> //定義函數模闆
T Min(T a, T b,T c)
{
if(a<b)
b=a;
return b<c?b:c; //傳回b、c中的小值
}
int main() //主函數
{
cout<<"使用模闆函數求不同類型資料的最小值"<<endl<<endl;
int i1 = 2, i2 = 6, i3 = 4;
double d1 = 3.4, d2 = 7.2, d3 = 3.39;
string str1("one"), str2("two"),str3("three");
cout << " int類型:"<<i1<<", "<<i2<<", "<<i3 <<" 最小值: " << Min(i1, i2, i3) << endl<<endl; //int型的最大值
cout << " double類型:" <<d1<<", "<<d2<<", "<<d3 <<" 最小值:" << Min(d1, d2, d3) << endl<<endl; //double型的最大值
cout << " string類型:" <<str1<<", "<<str2<<", "<<str3 <<" 最小值:"<< Min(str1, str2, str3) << endl<<endl; //string型的最大值
getchar();
return 0;
}
函數模闆個人覺得就是用來使代碼更加的簡潔,減少代碼的臃腫,同時為多種資料類型提供統一的解決方案。