函数模板的概念和意义

C++交换变量

  • 定义宏代码块 vs 定义宏函数
#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(int, a, b);
	Swap(a, b);
	
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	
	double m = 0;
	double n = 1;
	//SWAP(double, m, n);
	Swap(m, n);
	
	cout << "m = " << m << endl;
	cout << "n = " << n << endl;

	string d = "hello";
	string t = "world";
	
	Swap(d, t);
	
	cout << "d = " << d << endl;
	cout << "t = " << t << endl;	
	
	
    
    return 0;
}


宏代码块

  • 宏代码块
    • 代码复用,但缺少类型检查(编译器不知道红的存在)
  • 定义函数
    • 编译器堆类型检查,但无法代码复用

泛型函数的概念

  • 不考虑具体函数的编程方式
  • 对于Swap函数可考虑
void Swap(T& a, T&b)
 {
 	T t = a;
 	a = b;
 	b = t;
 }

T不是具体类型,泛指任意类型

  • 函数模板
  • 一种特殊函数可用不同类型进行调用
  • 类型可被参数化
template<typename T>
void Swap(T& a, T&b)
 {
 	T t = a;
 	a = b;
 	b = t;
 }
  • 函数模板规则
    在这里插入图片描述
  • 函数模板的使用
    • 自动类型推到调用
    • 具体类型推到调用

在这里插入图片描述

#include <iostream>
#include <string>

using namespace std;

#define SWAP(t, a, b) \
do              	   \
{						\
	t c = a;			\
	a = b;				\
	b = c;				\
}while(0)

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,4,3,2,1};

	Println(a, 5);
	
	Sort(a, 5);
	
	Println(a, 5);
	
	string s[5] = {"java", "C++" , "Basic", "c", "lua"};
	
	Println(s, 5);
	
	Sort(s, 5);
	
	Println(s, 5);
	
    return 0;
}


小结

  • 函数模板是泛型编程在C++中应用方式一
  • 函数模板能够根据实参堆参数类型进行推导
  • 函数模板支持显示指定参数类型
  • 函数模板是C++中重要的代码复用方式
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值