C + + templates and generics programming

Source: Internet
Author: User

Templates are the basis for generic programming in C + +. A template is a blueprint or formula that creates a class or function. When using generic types such as vectors or generic functions such as find, we provide enough information to convert the blue sky into a specific class or function. This conversion occurs at compile time.

Defining templates

-The two functions are almost identical, and the only difference is the type of the parameter, which is exactly the same as the function body

1 intCompareConst string&AMP;V1,Const string&v2)2 {3     if(V1 < v2)return-1;4     if(V2 < V1)return 1;5     return 0;6 }7 intCompareConst Double&AMP;V1,Const Double&v2)8 {9     if(V1 < v2)return-1;Ten     if(V2 < V1)return 1; One     return 0; A}

-"function template

-"We can define a generic function template instead of defining a new function for each type, a function template is a formula that can be used to generate a version of a function for a particular type." The compare version of the function may look like this

Template <typename t>       // template definition keyword template  parameter list <typename T,...; In the template definition, the Templates argument list cannot be empty  int Compare (constconst T &v2) {    ifreturn - 1 ;     if (V2 < V1) return 1 ;     return 0 ;}

Write here feel good tired, tomorrow in writing ...

C + + templates and generics programming

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.