C ++ getting started -- Template

Source: Internet
Author: User
Tags float max

C ++ getting started -- Template
Why template?

We have learned the Overloading feature. for heavy-duty functions, C ++ uses the correct matching of function parameters (number of parameters, parameter type) to call the heavy-load functions. For example, to obtain the maximum values of two numbers, we define the max () function to define different Overload versions for different data types.

 

// Function 1int max (int x, int y); {return (x> y )? X: y;} // function 2 float max (float x, float y) {return (x> y )? X: y;} // function 3 double max (double x, double y) {return (c> y )? X: y ;}

Now, let's review the above max () functions. They all have the same function, that is, to find the maximum value of two numbers, Can I write only one set of code to solve this problem?This will avoid calling errors caused by incomplete definition of the overload function (for example, if char a and B are defined separately, then max (a, B) is executed) the program will encounter errors, because we have not defined an overloaded version of the char type ).

 

Similarly, for classes, there are also the same problems (basically repetitive work ):

 

// Compare two integers to class Compare_int {public: Compare (int a, int B) {x = a; y = B;} int max () {return (x> y )? X: y;} int min () {return (x
 
  
Y )? X: y;} float min () {return (x
  
   

 

To solve these problems, C ++ introduces a template mechanism:A template is a tool for implementing the code reuse mechanism. It can implement type parameterization, that is, define the type as a parameter, thus realizing real code reusability.. Templates can be divided into two types: function templates and class templates.

 

Function Template

The function template is generally in the following format:

Template Return type function name (parameter table)

{

// Function Definition body

}

Template and class are keywords, and class can be replaced by typename. Here, typename and class are no different. <> the parameters in brackets are called template parameters. template parameters are similar to function parameters, the template parameter cannot be blank.

 

1. The class template is declared. You can use the template parameter name to declare the built-in type in the function.. The template parameters must be the template parameters provided when the template function is called to initialize the template parameters. Once the compiler determines the actual template parameters, it is called an instance of the function template.

 

template 
    
      void swap(T& a, T& b){//……}
    

 

When such a template function is called, type T is replaced by the called type. For example, swap (a, B) where a and B are int type, in this case, the form parameter T in the template function swap will be replaced by int, And the template function will be changed to swap (int & a, int & B ). When swap (c, d) Where c and d are double type, the template function will be replaced with swap (double & a, double & B ), in this way, the implementation of the function has nothing to do with the type.
 

The sample code is as follows:

 

# Include
    
     
Using std: cout; using std: endl; // declare a function template to compare the input values of two parameters of the same data type, // class can also be replaced by typename, and // T can be replaced by any letter or number. // Template
     
      
Template
      
       
T max (T x, T y) {return (x> y )? X: y;} int main () {int a = 2, B = 10; cout <"large integer:" <
       
        

 

The running result is as follows:

 

Class Template

The general form of a class template is as follows:

Template Class name {

// Class definition...

};

 

Once the class template is declared, you can use the form parameter name of the class template to declare the member variables and member functions in the class, that is, you can use the template parameter name to declare the built-in type in the class.For example:

 

template 
         
           class A{public: T a; T b; T hy(T c, T &d);};
         

 

Class A declares the member variables a and B of the two types of T, and declares A function hy with the return type T and two parameter types of T.

 

Create a class template object:For example, if A template class A is used, the method of using the class template to create an object isA M; Keep A <> angle bracket behind class A and fill in the corresponding type in it. In this way, all the parameters used in Class A will be replaced by int. When a class template has two template parameters, the method for creating an object isA M; Types are separated by commas.

 

The method for defining member functions externally in the class template is:

Template <template form parameter list> function return type class name <template form Parameter Name>: function name (parameter list) {function body}


For example, if there are two template parameters T1 and Class A of T2 contains A void h () function, the syntax for defining this function is:

 

template
         
           class A{public: void h();};template
          
            void A
           
            ::h(){// ……}
           
          
         

 

Note:The template declaration or definition can only be performed within the global, namespace, or class scope. That is, a template cannot be declared or defined in the main () function.

 

The sample code is as follows:

 

# Include
         
          
Using namespace std; template
          
           
Class Compare // class template {public: // Compare (numtype a, numtype B) {x = a; y = B;} Compare (numtype a, numtype B ); numtype max () {return (x> y )? X: y;} numtype min () {return (x
           
            
Compare
            
             
: Compare (numtype a, numtype B) {x = a; y = B;} int main () {Compare
             
              
Cmp1 (); // defines the object cmp1, used to compare the cout <cmp1.max () <"is the Maximum" <endl; cout <cmp1.min () <"is the Minimum" <endl; Compare
              
                Cmp2 (45.78, 93.6); // defines the object cmp2, used to compare two floating point numbers in cout <cmp2.max () <"is the Maximum" <
               
                 Cmp3 ('A', 'A'); // defines the object cmp3, used to compare two characters in cout <cmp3.max () <"is the Maximum" <
                
                 

 

 

The running result is as follows:

 

For sample code downloading in this tutorial, click here.

 

References:

 

Http://www.cnblogs.com/gw811

Http://www.cnblogs.com/gaojun

 

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.