泛型编程:c++中的表现为函数模板和类模板
1.发散性问题
c++中有几种交换变量的方法?
宏定义代码块 VS 定义函数
定义宏代码块:
—-优点:代码复用,适合所有类型
—-缺点:编译器不知道宏的存在,缺少类型检查
定义函数:
—-优点:真正的函数调用,编译器对类型进行检查
—-缺点:根据类型重复定义函数,无法代码复用
#include <iostream>#include <string>#include <sstream>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;}
2.新的需求
c++中有没有解决方案集合两种方案的有点?
3.泛型编程
概念:不考虑具体数据类型的编程方式
对于swap函数可以考虑以下的泛型写法
void swap(T& a,T& b)
{
T t = a;
a = b;
b = t;
}
4.c++中的泛型编程
—-函数模板
—-一种特殊的函数可用不同类型进行调用
—-看起来和普通函数很相似,区别是类型可被参数化
template<typename T>void swap(T& a,T& b){T t = a;a = b;b = t;}
template关键字用于声明开始进行泛型编程,tyapnamen用于声明泛指类型
5.函数模板的语法规则
—-template关键字用于声明开始进行泛型编程
—-typename关键字用于声明泛指类型
6.函数模板的使用:
—-自动类型推导调用
—-具体类型显示调用
int a = 0;
int b = 1;
Swap(a,b); //自动推导
float c = 2;
float d = 3;
Swap
#include <iostream>#include <string>#include <sstream>using namespace std;template<typename T>void Swap(T& a, T& b){T c = a;a = b;b = c;}int main(){int a = 0;int b = 1;Swap(a, b); //Swap<int>(a,b);cout << "a = " << a << endl;cout << "b = " << b << endl;double m = 2;double n = 3;Swap(m, n); ////Swap<double>(a,b);cout << "m = " << m << endl;cout << "n = " << n << endl;string d = "Delphi";string t = "Tang";Swap<string>(d, t);cout << "d = " << d << endl;cout << "t = " << t << endl;return 0;}
#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] << endl;}cout << endl;}int main(){int a = 0;int b = 1;swap(int, 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 c = "what's";string d = "up";Swap<string>(c, d); //显式调用cout << "c = " << c << endl;cout << "d = " << d << endl;string s[5] = {"Java","C++","Pascal","Ruby","Basic"};Println(s,5);Sort(s,5);Println(s, 5);return 0;}
小结
1.函数模板是泛型编程在c++中的应用方式之一(之二是类模板)
2.函数模板能够根据实参对参数类型进行推导
3.函数模板支持显示的指定参数类型
4.函数模板是c++中重要的代码复用方式
