下面是函数模板的实例,返回两个数中的最大值:
实例
#include<iostream>#include<string>usingnamespacestd; template <typenameT>inlineTconst& Max(Tconst& a, Tconst& b){ returna < b ? b:a; }intmain(){ inti = 39; intj = 20; cout << "Max(i, j): " << Max(i, j) << endl; doublef1 = 13.5; doublef2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; strings1 = "Hello"; strings2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return0;}
当上面的代码被编译和执行时,它会产生下列结果:
Max(i, j):39
Max(f1, f2):20.7
Max(s1, s2):World