/*
要建立一个模板, 关键字template和 class 是必须的!
除非可以使用关键字typename代替class,另外, 必须使用尖括号!
下面是一个模板:
template <class Any>
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
类型名可以任意选择, 这里为Any, 也可以是T.
模板并不创建任何函数, 只是告诉编译器如何定义函数。需要交换int的函数时,编译器将用int代
替Any。
此模板也可以这样写:
template <typename Any>
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
***若需要多个将同一种算法用于不同类型的函数,请使用模板!若不考虑向后兼容的问题,
并愿意键入较长的单词,则声明类型参数时,应使用关键词typename而不是class.
看个小程序:*/
/*
#include<iostream>
using namespace std;
template <class Any>
void Swap(Any &a, Any &b);
int main()
{
int i = 10;
int j = 20;
cout << "i, j = " << i << ", " << j << ".\n";
cout << "Using compiler_generated int swapper: \n";
swap(i, j);
cout <<"Now i, j = " << i << ", " << j << ".\n";
double x = 24.5;
double y = 81.7;
cout << "x, y = " << x << ", " << y << ".\n";
cout << "Using compiler_generated double swapper: \n";
swap(x, y);
cout << "Now.x, y = " << x << ", " << y << ".\n";
return 0;
}
template <class Any>
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}*/
/*
i, j = 10, 20.
Using compiler_generated int swapper:
Now i, j = 20, 10.
x, y = 24.5, 81.7.
Using compiler_generated double swapper:
Now.x, y = 81.7, 24.5.
Process returned 0 (0x0) execution time : 0.989 s
Press any key to continue.
*/
///这样看来, 模板真是个好东西呀!
///函数模板不能缩短可执行程序,最终的代码不包含任何模板, 只包含为程序生成的实际函数。
///1.重载的模板
///和常规重载一样,被重载的模板的特征标必须不同。
///并不是所有的模板参数都必须是模板参数类型
///再看个程序:
/*
#include<iostream>
using namespace std;
template <class Any>
void Swap(Any &a, Any &b);
template <class Any>
void Swap(Any *a, Any *b, int n);
void Show(int a[]);
const int Lim = 8;
int main()
{
int i = 10, j = 20;
cout <<"i, j = " << i << ", " << j << ".\n";
cout << "Using compiler_generated int swapper: \n";
swap(i, j);
cout << "Now i, j = " << i << ", " << j << ".\n";
int d1[Lim] = {0, 7, 0, 4, 1, 7, 7, 6};
int d2[Lim] = {0, 6, 2, 0, 1, 9, 6, 9};
cout << "Original arrays: \n";
Show(d1);
Show(d2);
Swap(d1, d2, Lim);
cout <<"Swapped arrays : \n";
Show(d1);
Show(d2);
return 0;
}
template<class Any>
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
template<class Any>
void Swap(Any a[], Any b[], int n)
{
Any temp;
for(int i=0; i<n; i++)
{
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void Show(int a[])
{
cout << a[0] << a[1] << "/";
cout << a[2] << a[3] << "/";
for(int i=4; i<Lim; i++)
cout << a[i];
cout << endl;
}
*/
/*
i, j = 10, 20.
Using compiler_generated int swapper:
Now i, j = 20, 10.
Original arrays:
07/04/1776
06/20/1969
Swapped arrays :
06/20/1969
07/04/1776
Process returned 0 (0x0) execution time : 0.338 s
Press any key to continue.
*/
函数模板(一)
最新推荐文章于 2023-05-22 19:44:26 发布