Usage of C + + templates

Source: Internet
Author: User

C + + in the high-level approach will be used in generic programming, there is a function template, the advantage of using templates in the program is that you do not need to specify a specific parameter type in the definition, but can be used to match any other type, the definition format is as follows

Template <class T>t func (t ...) {}

Let's look at a simple example, write a swap () to swap two integers for a position,

void swap (intint &b) {      int  tmp;      TMP  = A;       = B;       = A;       return 0 ;  }

If we were to exchange two floating-point numbers, the above swap () would not work, so we would have to write the following Exchange function

void swap (floatfloat &b) {     float  tmp;      TMP  = A;       = B;       = A;       return 0 ;  }

Obviously, the above two pieces of code in addition to the parameter types, the other processing is exactly the same, is not the sense of reusability of the code is very poor, if we want to exchange two long type number, no way, you can not write a swap (). Fortunately, C + + is smart enough, it has long provided us with a more flexible way to solve the above problem, that is the template. If you introduce a template, the above code can be replaced by the following break

Template <class t>void swap (t &a, T &b)   //T can be replaced by any type to achieve a generic effect {      T tmp;      TMP  = A;       = B;       = A;       return 0 ;  }

Main function

 int   main () { int  a=4 , b =5  ;  long  l1=3333 , L2 = 5455  ;  float  f1=234.53 , F2 = 34.552  ; Swap (A, b);      Compiler auto Generate a void swap (int &, int &) swap (L1,L2);   Swap (F1,F2);  //  A function can handle three types of parameters, which is the charm of the template  Span style= "color: #0000ff;" >return  0  ;}  

Note that a template can define multiple parameters at the same time, such as

Template <classclass T2, ....>T1 func (T2, ...) {}

Usage of C + + 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.