【情景引入】
问题:编写一个程序,输出同种类型两个变量的较大者。
实现:
1 #include <iostream> 2 3 using namespace std; 4 5 template <typename T> 6 const T& func(const T &a, const T &b) 7 { 8 return a >= b ? a : b; 9 } 10 11 int main() 12 { 13 int i1 = 10, i2 = 20; 14 double d1 = 3.14, d2 = 2.56; 15 string s1 = "ha", s2 = "hi"; 16 cout << func(i1, i2) << endl << func(d1, d2) << endl << func(s1, s2) << endl; 17 return 0; 18 }