function templates and Template functions
(1) Function template
Function templates can be used to create a common function that supports a number of different formal parameters and avoids repetitive design of function bodies that overload functions. Its greatest feature is the data type used by the function as a parameter.
The function template is declared in the following form:
Template<typename (or Class) t>
< return type >< function name > (parameter table)
{
function body
}
Where template is the keyword that defines a templated function; the angle brackets behind the templates cannot be omitted; TypeName (or Class) is the keyword that declares the parameter identifier of the data type, indicating that the identifier following it is the data type identifier. Such
In a later definition of this function, any variable that wishes to determine the data type based on the actual argument type can be described with the data type parameter identifier, so that the variable can be adapted to different data types. For example:
Template<typename (or Class) t>
T fuc (t X, t y)
{
T x;
......
}
A function template simply declares a description of a function as a template, not a function that can be executed directly, but only if the data type of the argument is used instead of the type parameter identifier in order to produce a real function.
(2) Template function:
The generation of template functions is the process of instantiating the type parameters of a function template.
#include <iostream>
Template <class t>
T My_min (t x,t y)//Take 2 number minimum value
{
Return (x<y)? x:y;
}
Template <class t>
void My_swap (T *x,t *y)//Exchange two numbers
{
T temp=*x;
*x=*y;
*y=temp;
}
int main ()
{
int i1=5,i2=6;
Double d1=6.5,d2=1.1;
using namespace Std;
cout<< "The smaller number is:" <<my_min (I1,I2) <<endl;
cout<< "The smaller Double is:" <<my_min (D1,D2) <<endl;
cout<< "i1=" <<i1<< ", i2=" <<i2<<endl;
cout<< "Results after Exchange" <<endl;
My_swap (&I1,&I2); The system will replace the T-generation function in the function template with the data type int of the argument I1,i2
My_swap (&D1,&D2); The system will use the data type of the argument d1,d2 double to replace the T generation function in the function template:
cout<< "i1=" <<i1<< ", i2=" <<i2<<endl;
cout<< "d1=" <<d1<< ", d2=" <<d2<<endl;
return 0;
}
C + + template learning one (function templates and templating functions)