C + + in the high-level approach will be used in generic programming, there is a function template, the advantage of using templates in the program is that you do not need to specify a specific parameter type in the definition, but can be used to match any other type, the definition format is as follows
Template <class T>t func (t ...) {}
Let's look at a simple example, write a swap () to swap two integers for a position,
void swap (intint &b) { int tmp; TMP = A; = B; = A; return 0 ; }
If we were to exchange two floating-point numbers, the above swap () would not work, so we would have to write the following Exchange function
void swap (floatfloat &b) { float tmp; TMP = A; = B; = A; return 0 ; }
Obviously, the above two pieces of code in addition to the parameter types, the other processing is exactly the same, is not the sense of reusability of the code is very poor, if we want to exchange two long type number, no way, you can not write a swap (). Fortunately, C + + is smart enough, it has long provided us with a more flexible way to solve the above problem, that is the template. If you introduce a template, the above code can be replaced by the following break
Template <class t>void swap (t &a, T &b) //T can be replaced by any type to achieve a generic effect { T tmp; TMP = A; = B; = A; return 0 ; }
Main function
int main () { int a=4 , b =5 ; long l1=3333 , L2 = 5455 ; float f1=234.53 , F2 = 34.552 ; Swap (A, b); Compiler auto Generate a void swap (int &, int &) swap (L1,L2); Swap (F1,F2); // A function can handle three types of parameters, which is the charm of the template Span style= "color: #0000ff;" >return 0 ;}
Note that a template can define multiple parameters at the same time, such as
Template <classclass T2, ....>T1 func (T2, ...) {}
Usage of C + + templates