When C ++ does not have a template mechanism, we use a common function. To implement an addition function, it can sum two parameters, and return values of the appropriate type based on the parameter type, you must manually write all the code:
Short sum (short a, short B) {return a + B ;}
Int sum (int A, int B) {return a + B ;}
Float sum (float a, float B) {return a + B ;}
......
Very troublesome. You can use the C ++ template function to express "general functions"
Template <typename T>
T Sum (t a, t B)
{
Return A + B;
}
Save as sumtest. h
Now, the C ++ compiler can generate an appropriate function based on the parameter type of the sum function, and then call it. For example:
# Include <iostream>
# Include "sumtest. H"
Using namespace STD;
Int main (void)
{
Float fa = 1, Fb = 3, FS;
FS = sum (FA, FB );
Cout <"sum (float, float) 1and 3 =" <FS <Endl;
}
[Root @ localhost HTML] # G ++-O sumtest. cpp
[Root @ localhost HTML] #./sumtest
Sum (float, float) 1 and 3 = 4
Based on the above Code, the C ++ compiler generates a "float version" sum function for us and calls it. If the parameter types are different, the compiler reports an error. For example
# Include <iostream>
# Include "sumtest. H"
Using namespace STD;
Int main (void)
{
Float fa = 1, FS;
Int IB = 3;
FS = sum (FA, IB );
Cout <"sum (float, INT) 1 and 3 =" <FS <Endl;
Return 0;
}
[Root @ localhost HTML] # G ++-O sumtest. cpp
Sumtest. cpp: In function 'int main ()':
Sumtest. cpp: 10: no matching function for call to 'sum (float &, int
&)'
Since the function template does not support the sum of two different types of parameters, the C ++ compiler will report that the true function cannot be generated, so that the programmer has the opportunity to know the call parameters except for the problem.
If a common function is used instead of a template function, compilation may be performed even if the parameter types are not completely consistent. For example
# Include <iostream>
Using namespace STD;
Float sum (float a, float B)
{
Return A + B;
}
Int main (void)
{
Float fa = 1, FS;
Int IB = 3;
FS = sum (FA, IB );
Cout <"sum (float, INT) 1 and 3 =" <FS <Endl;
Return 0;
}
[Root @ localhost HTML] # G ++-O sumtest. cpp
[Root @ localhost HTML] #./sumtest1
Sum (float, INT) 1 and 3 = 4
In C ++, the int type can be automatically converted to the float type, so no error is returned in this case.
The function template is not a real function. It is just a model for the c ++ compiler to generate a specific function. Therefore, the declaration and definition of function templates cannot be separated into different files, while common functions can do this.