Simple introduction and use of templates

Source: Internet
Author: User

What is a template?

Template refers to the function templates and class templates in C + +, which roughly correspond to the concepts of generics in C # and Java. Currently, templates have become an integral part of C + + generic programming.

The template definition starts with the keyword template, followed by the template parameter list, which is a comma-delimited set of one or more template parameters that are enclosed in angle brackets. A template parameter can be a type parameter that represents a type, or it can be a non-type parameter that represents a constant expression. A non-type parameter is followed by a type descriptor declaration. Type parameters are defined after the keyword class or TypeName ( as for the difference between class and TypeName, there is only class in earlier versions of C + + and no typename. In the vast majority of scenarios, both are common and only a few special cases must use TypeName. In short, the use of TypeName is foolproof. The difference between the two can be referred to this article ).

Templates are a great weapon for C + + programmers, especially after combining multiple inheritance (multiple inheritance) with operator overloading (operator overloading). The standard library of C + + provides many useful functions that mostly combine the concepts of templates, such as STL and IO Stream.

function Templates

The so-called function template, is actually to establish a general function, its function type and formal parameter type is not specified, with a virtual type to represent? This general function is called a function template? functions with the same function body can be replaced with this template, do not have to define multiple functions, just one in the template is defined once? When calling a function, the system replaces the virtual type in the template based on the type of the argument, thus enabling the functions of different functions.

Most of the online introduction is from the comparison of two number size, this article is still the case, assuming that there is a need to compare the size of two numbers, but the type of the two numbers is indeterminate, may be int, float, double type.

Of course there is a way that can be implemented by overloading the function, but the problem with overloading is: how many types of possibilities, how many overloaded functions will be written. Assuming that the current requirement may require only float and double two types, but one day increases the allowable for the int type, add an overloaded function to the int type parameter in the code.

At this point, the function template comes in handy. Just define a function with a generic parameter, you can implement a comparison of various types of parameters, see the following code directly:

  

1 classMyTemplate2 {3  Public:4MyTemplate (void);5~mytemplate (void);6 7     //<typename t> or <class t> return value type and parameter type are T after the start of the keyword template8Template <typename t>t Max (t a,t b)9     {Ten         returnA>=b?a:b; One     }; A};

The t here will be specific to the actual arguments that are passed into the code at the time the program is compiled, such as

If you compare the size of two int types:

    MyTemplate MyTemplate;     int Ten ;     int  - ;     int val = mytemplate. Max (x, y);    

The T in the program is replaced with int at compile time, and the replacement program should look like this:

int int Max (int A,int  b) {      return a>=b?   A:B; };

The same is true for float and double type, which is not repeated here.

Class template

When we have more complex requirements, for example to implement a queue, there may be more than one type of data in this queue, and there may be a string type, a double type, or a more complex custom type. For example, the following is a queue that stores objects of various data types, and you need to define a class template.

Simple queues implemented by class templates

1 #pragmaOnce2 3Template <typename t>classFzqueue;4Template <typename t>classQueueitem5 {6 Private:7Friendclassfzqueue<t>;//because Queueitem only fzqueue to be called directly, so here's to declare the friend of Fzqueue.8 9Queueitem (void){};Ten  OneQueueitem (ConstT &item1,ConstQueueitem *p): Item (ITEM1), next (p) {}; A  -Queueitem (ConstT &t): item (t), Next (0){};//explicitly define the copy constructor to set the item to t next to a null pointer -  the~queueitem (void){};// Destructors -  - T Item; -  +Queueitem *Next; - }; +  ATemplate <typename t> at classFzqueue - { -  Public: -Fzqueue (void): Head (0), Tail (0){}; -~fzqueue (void) -     { in destroy (); -     }; to      +     /*explicitly defining a copy constructor can have no effect on this feature without explicit declaration*/ -Fzqueue (ConstFzqueue &t): Head (0), Tail (0)//copying the value of each element in T to the newly declared object must be initialized to the pointer head and tail otherwise the memory access exception is reported when called the     { * copy_elements (t); $     };Panax Notoginseng  -fzqueue&operator=(Constfzqueue&);//An explicit assignment operator overload can have no effect on this feature without explicit declaration the  +t& Front ()//Get Queue Header A     { the         returnHead->item; +     }; -  $  $     voidPushConstT &item)//add elements to the end of a team -     { -Queueitem<t> *p_item =NewQueueitem<t>(item); the         if(Empty ()) -         {WuyiHead=tail=P_item; the         } -         Else Wu         { -Tail->next =P_item; AboutTail=P_item; $         } -     }; -  -     voidPop ()//Delete a queue header element A     { +Queueitem<t> *p_curhead =head; theHead=head->Next; - Delete p_curhead; $     }; the  the     BOOLEmpty ()//determine if the queue is empty the     { the         returnhead==0; -     }; in  the Private: theQueueitem<t> *head;//pointer to the queue header element About  theQueueitem<t> *tail;//pointer to the tail element of the team the  the     voidDestroy () +     { -          while(!empty ()) the         {Bayi pop (); the         } the     }; -  -     voidCopy_elements (ConstFzqueue &t) the     {         theQueueitem<t> *p =T.head; the         //int i = 0; the          while(p)/*i<5*/ -         { thePush (p->item); thep = p->Next; the             //i++;94         } the     }; the  the};
View Code

The calling code is as follows:

1 if(Valindexs.empty ())2     {3          for(intZi =Ten; zi!= the; zi++)4         {5 Valindexs.push (zi);6         }7     }8fzqueue<int>Clone_valzindexs (valindexs);9 Tencout<<"Valindexs:"<<valindexs.front () <<"______clone_valzindexs:"<<clone_valzindexs.front () <<Endl; One      Acout<<"Valindexs:"<<valindexs.front () <<"______clone_valzindexs:"<<clone_valzindexs.front () <<endl;
View Code

The above is the complete code to implement a simple queue with a class template.

Questions and summaries

1. The constructor overloads in the Class (Fzqueue (const T &t);) and operator overloading (fzqueue& operator= (const fzqueue&);) are removed and executed as normal. It is not known where this constructor overload and operator overloading are used.

Summary: Refer to "C + + Primer" in the fourth edition of the 13th chapter of the copy constructor described in the section, the description of the copy constructor is this:

A copy constructor is a special constructor that has a single formal parameter, which is a reference to the class type, which is a common const adornment. When you define a new object and initialize it with an object of the same type, the copy constructor is used explicitly. When you pass an object of that type to a function or return an object of that type from a function, the copy constructor is used implicitly. Available for:1. Displays or implicitly initializes an object based on another object of the same type 2. Copy an object and pass it as an argument to a function 3. Copy an object from the function return 4. Initializing elements in the sequential container 5. Initializing array elements based on element initializer list

Also: If the definition is not displayed in the program and the copy constructor is implemented, the compiler will generate it automatically. This is true for both assignment operator overloading and destructors.

You cannot declare a custom class as a pointer, such as Fzqueue<int> *clone_zindexs, and if you do, the copy constructor does not work when you call the copy constructor on the parameter, because only a pointer is declared here.

Simple introduction and use of templates

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.