C + + Primer Plus 14.4 class Template Learning Notes

Source: Internet
Author: User
Tags naming convention

14.4.1 Defining class Templates
The following is a template based on the stack class in the 10th chapter. The original class declaration is as follows:
typedef unsigned long Item;

Class Stack
{
Private
enum {MAX = 10}; Constant specific to Class
Item Items[max]; Holds stack items
int top; Index for top stack item
Public
Stack ();
BOOL IsEmpty () const;
BOOL Isfull () const;
Push () returns false if stack already is full, true otherwise
BOOL Push (const item & Item); Add Item to Stack
Pop () returns false if stack already is empty, true otherwise
BOOL Pop (item & Item); Pop Top into item
};
When a template is used, the template definition is used to replace the stack declaration and the member function of the stack is replaced with a template member function. Like template functions, the template class begins with the following faces:
Template <class type>
The keyword template tells the compiler that a template will be defined. The contents of the angle brackets are equivalent to the argument list of the function. The keyword class can be thought of as the type name of the variable, which accepts the type as its value, and the type as the name of the change amount.
Using class here does not mean that the type must be a class, but simply that the type is a generic type specifier, and when the template is used, it is replaced with the actual type. A newer C + + implementation allows the use of less confusing keyword typename instead of class in this case:
Template <typename type>//New Choice
You can use your own generic name instead of type, with the same naming convention as other identifiers. The current popular options include T and type. In a template definition, you can use a generic name to identify the type to store in the stack. For a stack, this means replacing all typedef identifier item in the declaration with type. For example
Item Items[max]; Holds stack items
should read:
Type Items[max]; Holds stack items
Similarly, you can replace the class method of the original class with a template member function. Each function header will begin with the same template declaration:
Template <class type>
You should also replace the typedef identifier with the generic name type item. Also, you need to change the qualifier from stack:: to Stack<type>::. For example
BOOL Stack::p ush (const item & Item)
{
...
}
should read:
Template <class type>//or template <typename type>
BOOL Stack<type>::p ush (const Type & Item)
{
...
}
If you define a method (inline definition) in a class declaration, you can omit the template prefix and the class qualifier.
Listing 14.13 lists the class templates and member functions. It is important to know that these templates are not class and member function definitions. They are C + + compiler directives that explain how to generate class and member function definitions. The specifics of a template are now--such as the stack class used to process a string object--called instantiation (instantiation) or materialization (specialization). Template member functions cannot be placed in a standalone implementation file. Because templates are not functions, they cannot be compiled separately. The template must be used in conjunction with a specific template instantiation request. The simplest way to do this is to put all the template information in a header file and include the file header in the file where you want to use the template.
Program Listing 14.13 Stacktp.h

//Stacktp.h--a stack template#ifndef Stacktp_h_#defineStacktp_h_Template<classType>classstack{Private:    enum{MAX =Ten};//constant specific to classType Items[max];//holds stack items    intTop//index for top stack item Public: Stack (); BOOLIsEmpty (); BOOLIsfull (); BOOLPushConstType & Item);//Add item to stack    BOOLPop (Type & Item);//Pop top into item};template<classType>Stack<Type>:: Stack () {Top=0;} Template<classType>BOOLStack<type>:: IsEmpty () {returntop = =0;} Template<classType>BOOLStack<type>:: Isfull () {returntop = =MAX;} Template<classType>BOOLStack<type>::p Ush (ConstType &Item) {    if(Top <MAX) {Items[top++] =item; return true; }    Else        return false;} Template<classType>BOOLStack<type>::p op (Type &Item) {    if(Top >0) {Item= items[--top]; return true; }    Else        return false;}#endif //Stacktp_h_


14.4.2 using template classes
You must request instantiation only if the program contains a template and cannot generate a template class. To do this, you need to live an object of type template class, by replacing the generic name with the specific type that you want. For example, the following code creates two stacks, one for storing int, and the other for storing a string object:
Stack<int> Kernels; Create a stack of ints
Stack<string> Colonels; Create a stack of string objects
When you see the above declaration, the compiler will press the stack<type> template to generate two separate class declarations and two separate sets of class methods.
Listing 14.14 modifies the original stack test program (program listing 11.12), using a string instead of a unsigned long value as the order ID.
Program Listing 14.14 Stacktem.cpp

//Stacktem.cpp--Testing the template stack class#include <iostream>#include<string>#include<cctype>#include"Stacktp.h"usingstd::cin;usingstd::cout;intMain () {Stack&LT;STD::string> st;//Create an empty stack    Charch; STD::stringPO; cout<<"Please enter a to add a purchase order.\n"<<"P to process a PO, or Q to quit.\n";  while(CIN >> ch && std::toupper (ch)! ='Q')    {         while(CIN.)Get() !='\ n')            Continue; if(!std::isalpha (CH)) {cout<<'\a'; Continue; }        Switch(CH) { Case 'A':             Case 'a': cout <<"Enter A PO number to add:"; CIN>>PO; if(St.isfull ()) cout<<"Stack already full\n"; ElseSt.push (PO);  Break;  Case 'P':             Case 'P':if(St.isempty ()) cout<<"Stack already empty\n"; Else{st.pop (PO); cout<<"PO #"<< PO <<"popped\n";  Break; }} cout<<"Please enter a to add a purchase order.\n"<<"P to process a PO, or Q to quit.\n"; } cout<<"bye\n"; return 0;}

Effect:

Please enter a to add a purchase order. P to process a PO, or Q to quit. Aenter a PO number to add:moonlightpoetplease enter a to add a purchase order. P to process a PO, or Q to quit. Aenter a PO number to add:moonlitplease enter a to add a purchase order. P to process a PO, or Q to quit. PPO #moonlit Poppedplease Enter a to add a purchase order. P to process a PO, or Q to quit. PPO #moonlightpoet Poppedplease Enter a to add a purchase order. P to process a PO, or Q to quit. Pstack already emptyplease Enter a to add a purchase order. P to process a PO, or Q to quit. Qbye

C + + Primer Plus 14.4 class Template Learning Notes

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.