为什么要有函数模板
需求:写 n 个函数,交换 char 类型、int 类型、double 类型变量的值。
函数模板定义形式
template < 类型形式参数表 >
类型形式参数的形式为:
typename T1 , typename T2 , …… , typename Tn 或 class T1 , class T2 , …… , class Tn
函数模板调用
myswap(a, b); //显示类型调用
myswap(a, b); //自动数据类型推导
案例:
#include <iostream>
using namespace std;
//提出问题:函数的业务逻辑一样,只是函数的参数类型不一样 有没有更好的机制
void myswap01(int &a, int &b)
{
int c = 0;
c = a;
a = b;
b = c;
}
void myswap02(char &a, char &b)
{
char c = 0;
c = a;
a = b;
b = c;
}
/*
让 类型参数化 === 方便程序员进行编码 这就是泛型编程
基本语法:template <typename T, typename T2>
template 告诉C++编译器 我要开始泛型编程了,不要随便报错
*/
template <typename T>
void myswap(T &a, T &b) //定义函数模板
{
T c;
c = a;
a = b;
b = c;
cout << "我是函数模板......" << endl;
}
//函数模板的调用
//1、显式类型 调用
//2、自动类型 推导(很少用)
void main()
{
{
int x = 10;
int y = 20;
myswap<int>(x, y); //1、显式类型 调用
cout << x << " " << y << endl;
myswap(x, y); //2、自动类型 推导
cout << x << " " << y << endl;
}
{
char a = 'a';
char b = 'b';
myswap<char>(a, b);
cout << a << " " << b << endl;
}
system("pause");
}
void main01()
{
int x = 10;
int y = 20;
myswap01(x, y);
cout << x << " " << y << endl;
{
char a = 'a';
char b = 'b';
myswap02(a, b);
cout << a << " " << b << endl;
}
system("pause");
}
函数模板的本质
函数模板的本质:函数类型参数化
案例:
#include <iostream>
using namespace std;
//函数模板的本质:函数类型参数化
//让你对字符数组 int数组进行排序
//泛型编程
template <typename T, typename T2>
int mySort(T *array, T2 size)
{
T2 i, j;
T temp = 0;
if (array == NULL)
return -1;
for ( i = 0; i < size; i++)
{
for ( j = i + 1; j < size; j++)
{
if (array[i] < array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return 0;
}
template <typename T, typename T2>
int myprint(T *array, T2 size)
{
T2 i;
for ( i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
return 0;
}
void main()
{
{
//int类型
int Array[] = { 11, 55, 66, 44, 33 };
int size = sizeof(Array) / sizeof(*Array);
mySort<int, int>(Array, size);
myprint<int, int>(Array, size);
}
{
//char类型
char buf[] = "abcdfghj";
int len = strlen(buf);
mySort<char, int>(buf, len);
myprint<char, int>(buf, len);
}
system("pause");
}