函数模板的概念和意义
Posted 学习只为旅行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数模板的概念和意义相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <string>
using namespace std;
#define SWAP(t, a, b) \\
do \\
{ \\
t c = a; \\
a = b; \\
b = c; \\
}while(0)
void Swap(int& a, int& b)
{
int c = a;
a = b;
b = c;
}
void Swap(double& a, double& b)
{
double c = a;
a = b;
b = c;
}
void Swap(string& a, string& b)
{
string c = a;
a = b;
b = c;
}
int main()
{
int a = 0;
int b = 1;
Swap(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
double m = 2;
double n = 3;
Swap(m, n);
cout << "m = " << m << endl;
cout << "n = " << n << endl;
string d = "Delphi";
string t = "Tang";
Swap(d, t);
cout << "d = " << d << endl;
cout << "t = " << t << endl;
return 0;
}
以上代码函数复制粘贴改类型,比较麻烦
#include <iostream>
#include <string>
using namespace std;
template < typename T >
void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
template < typename T >
void Sort(T a[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
if( a[i] > a[j] )
{
Swap(a[i], a[j]);
}
}
}
}
template < typename T >
void Println(T a[], int len)
{
for(int i=0; i<len; i++)
{
cout << a[i] << ", ";
}
cout << endl;
}
int main()
{
int a[5] = {5, 3, 2, 4, 1};
Println(a, 5);
Sort(a, 5);
Println(a, 5);
string s[5] = {"Java", "C++", "Pascal", "Ruby", "Basic"};
Println(s, 5);
Sort(s, 5);
Println(s, 5);
return 0;
}
小结
以上是关于函数模板的概念和意义的主要内容,如果未能解决你的问题,请参考以下文章