#include<iostream> #include<string> using namespace std; template<typename T> T maxValue(T value1,T value2) { return value1>=value2 ? value1:value2; } template<typename T> void sort(T list[],int arraySize) { for(int i=arraySize-1;i>=1;i--) { //find the maximun in the list[0..i] T currentMax = list[0]; int currentMaxIndex = 0; for(int j=0;j<=i;j++) { if(currentMax<list[j]) { currentMax = list[j]; currentMaxIndex = j; } } if(currentMaxIndex!=i) { list[currentMaxIndex] = list[i]; list[i]=currentMax; } } } template<typename T> void printArray(T list[],int arraySize) { for(int i=0;i<arraySize;i++) { cout<<" "<<list[i]<<" "; } cout<<endl; } int main() { cout<<"maxValue(1,2) :/t"<<maxValue(1,2)<<"/n"; cout<<"maxValue(2.1,2.0):/t"<<maxValue(2.1,2.0)<<"/n"; cout<<"maxValue('a','d'):/t"<<maxValue('a','d')<<"/n"; int list1[5] = {1,3,4,2,9}; sort(list1,5); printArray(list1,5); double list2[6] = {3.3,4.4,2.4,2.2,1.1,4.2}; printArray(list2,6); sort(list2,6); printArray(list2,6); system("pause"); return 0; } /* Templates provide the capability to parameterize types in functions and classes . With this capability you can define one function or one class with a generic type that can be substituted for a concrete type by the compiler. 使用g++编译执行结果 C:/Documents and Settings/Administrator C:/Documents and Settings/Administrator>d: D:/>cd D:/My Documents/study files/C++ D:/My Documents/study files/C++>g++ template.cpp -o template D:/My Documents/study files/C++>template maxValue(1,2) : 2 maxValue(2.1,2.0): 2.1 maxValue('a','d'): d 1 2 3 4 9 3.3 4.4 2.4 2.2 1.1 4.2 1.1 2.2 2.4 3.3 4.2 4.4 请按任意键继续. . . */