C + + generic programming and template learning

Source: Internet
Author: User

Generic programming, English called Generic programming

Can be understood as, universal meaning, universality, programming.

For example, you would implement a function to compare the size of two numeric values, which could be either int or string. For the first attempt, we intuitively think of defining multiple overloaded functions. As follows:

int compare (const string &V1, const string &v2)

{

if (V1 < v2) return-1;

if (V2 < v1) return 1;

return 0;

}

int compare (const int &V1, const int &V2)

{

if (V1 < v2) return-1;

if (V2 < v1) return 1;

return 0;

}

These two functions are almost identical except for the type of the parameter. As the types of comparisons increase, we have to define a number of similar and redundant functions.

Generic programming is designed to solve such problems, so that we can write code independently of any particular type.

Templates are the basis for C + + generic programming. The template definition starts with the keyword template followed by a list of templates parameters. The template parameter list is surrounded by <> with one or more template parameters separated by commas.

For example, the above requirements can be written as follows:

Template <typename t>

int compare (const t &V1, const T &V2)

{

if (V1 < v2) return-1;

if (V2 < v1) return 1;

return 0;

}

C + + generic programming and template learning

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.