C + + notes------templates

Source: Internet
Author: User

Templates are-----to make the code more generic, so that the code is not affected by the data type. Reduce code redundancy. The template passes the data type as a parameter. Includes function templates and class template.

Function templates:

//define a comparative size function templateTemplate<typename type>//can also be written as template <class type>type Max (type A,type b) {returna > B?a:b;}intMain () {cout<< Max (1,2) <<Endl; cout<< Max ('A','a') <<Endl; cout<< Max (2.5,3.2) <<Endl; return 0;}

The template will automatically deduce the data type based on the passed arguments, for example, in Max (2.5,2.3), the template will be double based on 2.5, and the template will deduce that the ype is a double type, generate a template function, and use a comparison function of type Double. So the template, although convenient, but not high efficiency.

For example, when you call the function Max, the compiler makes a template function of type int. Then go to invoke the specific template function.

Stencil functions
int Max (intint b) { return a > B? a:b}

When the actual parameter type is inconsistent, the normal function runs normally, and the template will have errors, such as:

/*
Template<typename type> //will produce ambiguity type Max (type A,type b) { return a > B? a:b;}
*/ int Max (int A,int b) //will automatically be converted implicitly {return a > b? a:b;} int Main () { << Max (1,2.3) << Endl;
cout << Max (1, (int) 2.3) << Endl; Cast 2.3 to int type
cout << max<int> (1,2.3) << Endl; Specify a template function that calls int type}

You can also rewrite the template functions, such as:

Template<typename Type1, TypeName type2>Type2 Max (Type1 a,type2 b) {    return a > B? A: b;}

If you are comparing a class object, you need to overload the comparison operator. Templates are only responsible for comparisons, regardless of how they are compared.

classtest{intnum; Public: Test (intb): num (b) {}BOOL operator> (ConstTest &t) {if( This->num >t.num)return true; Else             return false; }};template<typename type1>Type1 Max (Type1 a,type1 b) {returna > B?a:b;}intMain () {Test T1 (Ten); Test T2 (9);  Max (T1,T2); Cannot use cout output because the << operator function is not provided}

Class Template:

Simple implementation of linear linked list using class template.

int a = int (); Initialize a to 0;
Template class member functions are template functions and do not allow separation of class definitions and implementations

#include <iostream>using namespacestd;//declaring the list class template<typename type>classList;
Template<typename type>classlistnode{Private: Type data; ListNode<Type> *Next; Public: FriendclassList<type>; The list class becomes a friend of the ListNode class in order to access the private Data ListNode ():d ATA (Type ()), Next (NULL) {}//0 initialization: Initializes according to the different types. For example, int a = INT ()//a is initialized to 0. ListNode (Type d,listnode<Type> *n =NULL):d ata (d), Next (n) {}~ListNode () {}};template<typename type>classlist{Private: ListNode<Type> *First ; ListNode<Type> *Last ; size_t size; Public: List (); ~List (); BOOLpush_back (Type x); Trailing insert linked list
Display list FunctionsvoidShow_list ()a const//template class member function can be defined inside a class{ListNode<Type> *p=First ; while(P! =NULL) {cout<< p->data; P= p->Next; }}};templateThe member functions of the <typename type>//template class are template functions, so you must write Template<typename type>List<Type>:: List ()//limit is list<type>::{ first= last =NewListnode<type>; Last->next =NULL; Size=0;} Template<typename type>List<type>::~List () {ListNode<Type> *p=First ; while(P! =NULL) { First= p->Next; Deletep; Use new in constructors, use delete size in destructors--; P=First ; }}template<typename type>BOOLList<type>::p ush_back (Type x) {ListNode<Type> *s =NewListnode<type>; if(s = =NULL)return false; S->data =x; S->next =NULL; Last->next =s; Last=s; return true;}intMain () {List<int>MyList; for(intI=1;i<Ten; i++) {mylist.push_back (i); } mylist. Show_list (); return 0;}

C + + notes------templates

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.