c++函数模板
函数模板存在的意义;如果同一函数,参数类型有所不同,相同的功能可能会定义多个函数实例,这十分繁冗
#include<iostream> using namespace std; void swap(int &a,int &b) { int temp = a; a = b; b = temp; } void swap(char &a, char &b) { char temp = a; a = b; b = temp; } void main() { int a = 8,b=10; swap(a,b); cout << "a----" << a << "b---" <<b << endl; char *x = "陈培昌"; char *y = "付高峰"; swap(x,y); cout << "x----" << x << "y---" << y << endl; system("pause"); }
输出结果
- 定义函数模板
#include<iostream> using namespace std; template <typename T> void myswap(T &a,T &b) { T c; c = a; a = b; b = c; } void main() { int a = 8; int b = 10; myswap<int>(a,b); cout << "a----" << a << "b---" <<b << endl; char *x = "陈培昌"; char *y = "付高峰"; //cout << "x----" << x << "y---" << y << endl; myswap<char*>(x, y); cout << "x----" << x << "y---" << y << endl; system("pause"); }
输出结果: