函数模板
函数模板和普通函数的区别以及调用规则
模板的实现机制
模板局限性
#include<iostream> #include<string> using namespace std; class person { public: string name; int age; person(string name, int age) :name(name),age(age){} }; template<typename T> void mySwap(T &a,T &b) { T temp = a; a = b; b = temp; } template<class T> void arr_sort(T arr[],int len) { for (int i = 0;i<len;i++) { for (int j = i+1;j<len;j++) { if (arr[i]<arr[j]) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } template<class T> void print_arr(T arr[],int len) { for (int i = 0; i < len;i++) { cout << arr[i] << " "; } } template<class T> bool compare_obj(T &a,T &b) { if (a==b) { return true; } return false; } //对复杂数据类型具体化 template<> bool compare_obj(person &a,person &b) { if (a.age==b.age&&a.name==b.name) { return true; } return false; } void test() { int a = 10; int b = 20; mySwap(a, b); cout << a << endl; cout << b << endl; double c = 3.14; double d = 1.2; mySwap<double>(c, d); cout << c << endl; cout << d << endl; char str[10] = "abcdefg"; arr_sort(str,strlen(str)); print_arr(str,strlen(str)); int arr[10] = { 1,5,3,7,2,8,9,19,12,30 }; arr_sort(arr, 10); print_arr<>(arr, 10); person p1("Tom", 21); person p2("Tom", 21); cout << "\nresult: " << compare_obj(p1, p2) << endl; } int main() { test(); system("pause"); return EXIT_SUCCESS; }