Template is the unique features of C + +, it is also a relatively difficult place in C + +, I usually develop the time with very little, or almost no use, need template is the place to understand the framework of the relevant code;
Template function is relatively simple, the introduction of the template is the purpose of code reuse, such as the algorithm is similar, but because the data type is different, we have to copy the same copy of the Code two times, and just to modify the data type, then after the introduction of the function template, we can only use a copy of the code to represent different overloaded functions.
Here's an introduction to the simplest function templates:
Template <typename t> //define an abstract data type T
T Mymax (t A, T b) { //Declare function template
Return a > B? A:B;
}
int main () {
int a = 2;
int b = 3;
Std::cout<<mymax (A, b) <<std::endl; //dynamic generation function int Mymax (int, int)
float C = 2.0f;
float d = 3.0f;
Std::cout<<mymax (c, D) <<std::endl; //Dynamic generation function Flota Mymax (float, float)
}
When the code calls the Mymax () function for the first time, its arguments are int, the compiler infers that the template parameter T is int, and the compiler takes the function template as a template, substituting the abstract type T in the function template with the actual type int, and automatically generates a version of type int for the function call.
Simple use of C + + function templates