We know that C ++ has the function overload concept. The function overload function is to rewrite a function multiple times so that it can have multiple types of parameters. Simply put, multiple functions are defined using the same function name. The number and type of parameters of these functions are different.
Using the function template, you can easily implement the parameter requirements of different functions. In fact, function templates and function overloading are very similar. The only difference is that function overloading requires writing multiple functions, while function templates only need to write one function template (special functions) you can match parameters of any type during the call!
For example:
We need to write a maximum function (max ()):
Max (int a, int B, int x ){
If (a> B) {x =;
} Else {x = B;
}
Return x;
}
In this way, we can calculate the maximum value of an integer (int), but another problem is that if we declare a function in this way, we must declare multiple types of functions, that is to say, this int type function can only work for int type data. If it is a double long or other types, it does not apply. As follows:
Max (dobule a, ouble B, double x ){
If (a> B) {x =;
} Else {x = B;
}
Return x;
}
Of course we can define multiple functions for implementation, but there will be too much redundant code. Therefore, we must use the function template to solve this problem:
# Include "stdafx. h"
# Include <iostream>
# Include <cmath>
Using namespace std;
Template <class T>
T max (T a, T B, T c ){
If (a> B ){
C =;
} Else
{
C = B;
}
Return c;
}
Int main (){
Int I = 0;
Double d = 0;
Int x = 1, y = 2, z = 0;
Double q = 1.1, w = 2.2, e = 0;
I = max (x, y, z );
D = max (q, w, e );
Cout <"I =" <I <endl;
Cout <"d =" <d <endl;
Return 0;
}
In this way, functions of the same function can process different types of parameters!
You can understand the meaning of the function template after completing this example! I can't explain it more.
To sum up, "the function is to make the function that agrees to the function adapt to different parameter types"
Author Bai Lu