Simple use of C + + function templates

Source: Internet
Author: User

Template is the unique features of C + +, it is also a relatively difficult place in C + +, I usually develop the time with very little, or almost no use, need template is the place to understand the framework of the relevant code;

Template function is relatively simple, the introduction of the template is the purpose of code reuse, such as the algorithm is similar, but because the data type is different, we have to copy the same copy of the Code two times, and just to modify the data type, then after the introduction of the function template, we can only use a copy of the code to represent different overloaded functions.

Here's an introduction to the simplest function templates:

Template <typename t> //define an abstract data type T

T Mymax (t A, T b) { //Declare function template

Return a > B? A:B;

}

int main () {

int a = 2;

int b = 3;

Std::cout<<mymax (A, b) <<std::endl; //dynamic generation function int Mymax (int, int)

float C = 2.0f;

float d = 3.0f;

Std::cout<<mymax (c, D) <<std::endl; //Dynamic generation function Flota Mymax (float, float)

}

When the code calls the Mymax () function for the first time, its arguments are int, the compiler infers that the template parameter T is int, and the compiler takes the function template as a template, substituting the abstract type T in the function template with the actual type int, and automatically generates a version of type int for the function call.

Simple use of 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.