C++ function template introduction
Introduction of function templates
Generally speaking, when we write a function, its parameter types are determined. For example, the following function prototype:
void Swap(int &a,int &b);
As you can see from the function prototype, this is a swap function. The function is to exchange the incoming values of a and b.
But we can also see that the parameters passed in are all of int type, so only two int values can be exchanged.
So the question is: If I pass two double variables, do I have to write another function (of course, using function overloading can indeed reflect the polymorphism of C++), but what about other types? long, sort, long long...
So we need to introduce another concept- template to achieve such a function, so that we only write a function to complete the input of all generic parameters.
Function template keyword-template
The keyword of the function template is-template
template <typename AnyType>
void Swap(AnyType &a,AnyType &b)
{
AnyType temp;
temp=a;
a=b;
b=temp;
}
As you can see from the above code, a generic type is defined by the keyword template and defined by the keyword typename , where AnyType is just a name, any C++ canonical naming, such as "T" (and this naming is also more Common) can also
template <typename T>
example
Now we, through an example to see the definition and use of the template function
#include<iostream>
using namespace std;
template <typename T>
void Swap(T &a,T &b);
int main()
{
int i=10;
int j=20;
cout<<"i,j="<<i<<","<<j<<".\n";
cout<<"Using compiler generated int swapper:\n";
Swap(i,j);
cout<<"Now i,j="<<i<<","<<j<<".\n";
double x=24.5;
double y=81.7;
cout<<"x,y="<<x<<","<<y<<".\n";
cout<<"Using compiler generated double swapper:\n";
Swap(x,y);
cout<<"Now x,y="<<x<<","<<y<<".\n";
return 0;
}
template <typename T>
void Swap(T &a,T &b)
{
T temp;
temp=a;
a=b;
b=temp;
}
After running, the output: As
you can see, the Swap function is called twice, once with int type and once with double type, but only one function is written, which saves a lot of code
———————————————————————————————————————————————— ————————————————————
Reference book: "C++ Primer Plus 6th"