C++基础:模板:函数模板和类模板

来源:互联网 发布:大数据与传统制造业 编辑:程序博客网 时间:2024/06/05 04:32
模板:

为了代码重用,代码就必须是通用的;通用的代码就必须不受数据类型的限制。


那么我们可以把数据类型改为一个设计参数。这种类型的程序设计称为参数化(parameterize) 程序设计。


软件模块由模板(template) 构造。包括函数模板(function template)和类模板(class template)。


建议阅读C++ Templates 1--7 章


1.函数模板:

例1:

<span style="font-size:18px;">template<typename Type>Type Max(Type a, Type b){cout<<typeid(Type).name()<<endl;     //查看类型return a > b ? a : b;}int main(){Max(1,2);Max(1.2,2.3);    //模板可以自动推演参数的类型//Max(1,2.3);   //错误,参数的类型不同,会引起模板的二义性,模板不支持隐式转换Max(1,(int)2.3);Max<int>(1,2.3);  //显式提供参数类型return 0;}</span>
例2:

<span style="font-size:18px;">template<typename Type1, typename Type2>  Type1 Max(Type1 a, Type2 b){return a > b ? a:b;}int main(){Max(1,1.2);   //参数类型不同}</span>
例3:


<span style="font-size:18px;">class Test{public:bool operator>(const Test &t){return true;}};temple<typename Type>Type Max(Type a, Type b){return a > b ? a : b; }int main(){Test t1, t2;Max(t1, t2);return 0;}</span>

由函数模板生成的函数叫模板函数;
模板调动效率不高:因为系统底层需要根据类型的不同生成相对应的模板函数;


2.类模板与线性表


<span style="font-size:18px;">#include <iostream>using namespce std;template<typename Type>class List;template<typename Type>class ListNode{friend class List<Type>;public:ListNode():data(Type()),next(NULL)    //零初始化{}ListNode(Type d, ListNode<Type> *n = NULL):data(d),next(n){}~ListNode(){}private:Type data;ListNode<Type> *next;};template<typename Type>class List{public:List();bool push_back(Type x);void show_list()const;private:ListNode<Type> *first;ListNode<Type> *last;size_t          size;};template<typename Type>List<Type>::List(){first = last = (ListNode<Type>*)malloc(sizeof(ListNode<Type>));last->next = NULL;size = 0;}template<typename Type>bool push_back(Type x){ListNode<Type> *s = (ListNode<Type>*)malloc(sizeof(ListNode<Type>));if(s == NULL){return false;}s->data = x;s->next = NULL;last->next = s;last = s;size++;return true;}template<typename Type>void List<Type>::show_list()const{ListNode<Type> *P = first->next;while(p != NULL){cout<<p->data<<"-->";p = p->next;}cout<<"Nul."<<endl;}int mian(){List<int> mylist;for(int i = 1; i < 10; ++i){mylist.push_back(i);}return 0;}</span>



0 0
原创粉丝点击