Function templates are widely used in actual programs because of their own characteristics: After defining a function body, you can call them multiple times for instantiation.
Example:
[Cpp]
# Include <iostream>
Using namespace std;
Template <typename T, int size> // function template parameters, including type parameter T and value parameter size
Int find (T (& array) [size], T var) // defines the search function: find the element var in the T-type array
{
For (int I = 0; I <size; I ++)
{
If (var = array [I])
Return I + 1;
}
Return-1;
}
Int main ()
{
Int a [5] = {3, 2, 4, 5, 1 };
Double B [6] = {1.0, 2.1, 3.2, 4.3, 5.4, 6.5 };
Cout <"position of integer 1:" <find (a, 1) <endl;
Cout <"floating point 4.3 position:" <find (B, 4.3) <endl;
System ("pause ");
}
Output:
Note that the operator & is used before the array. This is the address operator. You can pass the first address of the array in the real parameter.