模板,泛型
#include <iostream> #include <string> using namespace std; // 模板,泛型的使用,template <typename T> 是固定写法,T 可以换成其他字母 template <typename T> T max(T a, T b) { return a > b ? a : b; } // 使用泛型来适应不同的数据类型,否则要用方法重载来实现 int main() { int i = 10; int j = 6; cout << max(i, j) << endl; float a = 10.2; float b = 14.2; cout << max(a, b) << endl; string str1 = "hello"; string str2 = "world"; cout << max(str1, str2) << endl; system("pause"); return 0; }
运行: