C ++ Primer learning note _ 45 _ template (III): Default template parameters (Stack template is implemented using the standard template container deque), member template, and keyword typename

Source: Internet
Author: User

C ++ Primer learning note _ 45 _ template (III): Default template parameters (Stack template is implemented using the standard template container deque), member template, and keyword typename
1. Default template parameters

1. Can stack memory be managed using standard template containers? The answer is yes. You only need to pass one more template parameter, and the template parameter can also be the default one, as shown below:

 

Template
 
  
> // There must be spaces at the end of the Code. Otherwise, the compilation fails. class Stack {... Private: CONT c _;};
 

 

If the second parameter is not passed, the default value is deque dual-end queue. Of course, std: vector can also be passed.

 

2. Example: Implement stack template class by using standard template container deque Management

The Stack here is an adapter, one of the six major STL components, code reuse, not inheritance; implement a template class through the existing class

Stack. h:

 

# Ifndef _ STACK_H _ # define _ STACK_H _ # include
 
  
# Include
  
   
Using namespace std; template
   
    
> // There must be spaces at the end of the Code. Otherwise, the compilation fails. class Stack {public: Stack (): c _(){}~ Stack () {} void Push (const T & elem) {c _. push_back (elem);} void Pop () {c _. pop_back ();} T & Top () {return c _. back ();} const T & Top () const {return c _. back ();} bool Empty () const {return c _. empty ();} private: CONT c _; // stack management with standard template container deque}; # endif // _ STACK_H _
   
  
 

 

Main. cpp:

 

# Include "Stack. h" # include
 
  
# Include
  
   
Using namespace std; int main (void) {// Stack
   
    
S; // The default value is deque.
    
     
> S; s. Push (1); s. Push (2); s. Push (3); while (! S. Empty () {cout <s. Top () <endl; s. Pop () ;}return 0 ;}
    
   
  
 

 

The output is 3 2 1.

That is, if the second parameter is not passed, operations such as stack and pressure stack call deque directly. By deque. Memory Management.

For example, transfer a vector in a program By the vector Member function processing.

 

 

Ii. Member templates

Let's look at the following example:

 

#include 
 
  using namespace std;template 
  
   class MyClass{private:    T value;public:    void Assign(const MyClass
   
     &x)    {        value = x.value;    }};int main(void){    MyClass
    
      d;    MyClass
     
       i;    d.Assign(d);        // OK    d.Assign(i);        // Error    return 0;}
     
    
   
  
 

 

Compilation errors may occur because I and d are of different types. You can use a member template to solve the problem:
# Include
 
  
Using namespace std; template
  
   
Class MyClass {private: T value; public: MyClass () {} template
   
    
MyClass (const MyClass
    
     
& X): value (x. GetValue () {} template
     
      
Void Assign (const MyClass
      
        & X) {value = x. getValue (); // when values of different types are private, use the member function call} T GetValue () const {return value ;}}; int main (void) {MyClass
       
         D; MyClass
        
          I; d. Assign (d); // OK d. Assign (I); // OK MyClass
         
           D2 (I); return 0 ;}
         
        
       
      
     
    
   
  
 
To support MyClass D2 (I); therefore, the copy constructor must also be implemented as a member template function. Similarly, if you want to support d = I, you must also implement the value assignment operator as a member template. In fact, auto_ptr The member template is used for implementation in, because it must support operations similar to the following: Auto_ptr X; Auto_ptr Y; X = y; 3. For the typename keyword, see the following example: typenameT: SubType * ptr, subType is considered as a static data member of the T type. After derivation, * is not regarded as a pointer, but is considered as a multiplication number, and an error occurs during compilation. After modification, we can see that SubType is a custom type within T, ptr is a pointer to this type, and the compilation passes.
# Include
 
  
Using namespace std; template
  
   
Class MyClass {private: typename T: SubType * ptr _;}; class Test {public: typedef int SubType; // If the SubType type is not defined in Test, compilation will fail}; int main (void) {MyClass
   
    
Mc; return 0 ;}
   
  
 
Iv. Derived classes and templates, object-oriented and generic programming

(1) Derived classes and templates

1. To improve the running efficiency, the class templates are independent of each other, that is, they are designed independently without the idea of inheritance. The class template is extended using an adapter (such as the previous use of deque for Stack ). Universality is one of the starting points of the template library design, which is achieved by means of generic algorithms (algorithm) and function objects (functor.


2. One of the goals of derivation is code reuse and program universality. The most typical is MFC. The advantage of a derived class is that it can be simplified to complex and gradually deepened, the previous work can be fully utilized in the programming process to complete a complex task step by step.


3. templates aim for operational efficiency, while derivation pursues programming efficiency.

 

(2) Object-oriented and generic programming

1. object-oriented and generic types depend on certain forms of Polymorphism

(1) Object-oriented

Dynamic polymorphism (virtual function)

(2) Generic

Static polymorphism (template class, template function)

2. There is an inheritance relationship between the application with polymorphism in the object-oriented model at runtime. We write code that uses these classes to ignore the type differences between the base class and the derived class. As long as the base class pointer or reference is used, the base class type object and the derived class type object can share the same code.


3. In generic programming, the classes and functions we write can be used for non-relevant types during compilation. A class or function can be used to manipulate multiple types of objects.

Refer:

C ++ primer version 4
Valid tive C ++ 3rd
C ++ programming specifications

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.