C + + function templates

Source: Internet
Author: User

If you compare two different types of values, you might write out the following code:

int Compare (conststringconststring &v2) {    if (V1 < v2) {        return -1;    }     if (V2 < v1) {        return1;    }     return 0 ;}
int Compare (constdoubleconstdouble &v2) {    if (V1 < v2) {        return -1;    }     if (V1 > v2) {        return1;    }     return 0 ;}

These two functions are not the same as the numerical comparison class, the function body is the same, and rewrite the trouble.

We need the template now.

Template <typename t>int Compare (constconst T &v2) {    if ( V1 < v2) {        return -1;    }     if (V1 > v2) {        return1;    }     return 0 ;}

It can be done with a function body, which is called a generic function template.

1. Definition

The template definition starts with a keyword, followed by the templates parameter list, which is a comma-delimited list of one or more stencil parameters, wrapped with less than < and greater than sign >.

2. Instantiation

When the template is defined, the call is instantiated.

cout << Compare (12) << Endl; // Compare (const int &V1, const int &v2)

Because the compiler encounters a template definition, it does not generate code. The compiler generates code only when you instantiate a specific version of the template. This feature affects how we organize the code and when the error is detected.

C + + function 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.