1. Function Template
The function template allows multiple function definitions to be simplified and described in a unified function definition form. In fact, the function template represents a group of functions with the same name. These functions with the same name are all overload functions.
Function templates are defined in the following forms:
Template <template parameter table>
Function type identifier function name (form parameter list)
{
// Function body
}
2. template Functions
A function template is a template definition that specifies common function parameters. The function template can only be defined once. It establishes a general function that can execute the same operation on different data types. The function template definition is just a common function definition. The C ++ compiler does not generate anyProgramCode. In the C ++ program, you can specify a specific data type for the class type of the function template. The C ++ compiler checks whether the specified parameter type matches the class property when calling the function template in a program. If yesReplace the class type with this real parameter type to generate an actual function definition, which is called a template function.This process is the function template definition instantiation. The C ++ compiler compiles the newly created template function, which is an overloaded function.
In fact, the C ++ compiler first tries to match the general overload function when processing the overload function. If it does not match, it tries to match the function template. If it does not match, it is also possible to perform necessary and feasible implicit type conversion for the parameter types in general overload functions before matching.
Example:
# Include <iostream>
# Include <string. h>
Using namespace STD;
Template <typename T>
T fun (t a, t B)
{
Return A + B;
}
Int fun (int A, int B)
{
Return A-B;
}
Int main ()
{
Int A = 20, B = 40;
Float c = 2.4, D = 8.9;
Int result = fun (A, B );
Float r = fun (c, d );
Printf ("result = % d, r = % F \ n", result, R );
Return 0;
}
Program result, result =-20, instead of 60. R = 11.300000.