C + + (use of function templates)

Source: Internet
Author: User

Function templates can be used to create a common function to support multiple different parameters and avoid repetitive design of function bodies that overload functions. The most important feature of this is the function of the practical data type as a parameter.

The general form of defining a function template is:

Template<typename t>

Or

Template<class t>

1 Let's try to use function overloading to define different types of functions

Int:

int int_add (int a,intb)

{

int C;

c = a + B;

return C;

}

Double

Double Double_add (double a;double b)

{

Double C;

c = a + B;

return C;

}

int main ()

{

Cout<<int_add (5,3) <<endl; Call the Int_add function

Cout<<double (5.1,3.1) <<endl; Call the Double_add function

return 0;

}

2 Also we can use constructors to do the same things

#include <iostream>
using namespace Std;
int n_add (int a,int b)//define function N_add for int type data addition
{
int C;
C=a+b;
return C;
}
Double N_add (double a,double b)//define function N_add for double type function addition
{
Double C;
C=a+b;
return C;
}
int main ()
{
Cout<<n_add (5,3) <<endl; Call the N_add function
Cout<<n_add (5.35,5.5) <<endl; Call the N_add function
return 0;
}

3 Using Function templates

#include <iostream>

using namespace Std;

Template<typename t>

T N_add (t a,t b)

{

T C;

c = a + B;

return C;

}

int main ()

{

Cout<<n_add (5,3) <<endl;

Cout<<n_add (5.1,3.1) <<endl;

return 0;

}

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