When C + + does not have a template (template) mechanism, we use the ordinary function, we want to implement an addition function, he can sum two parameters, and according to the type of parameter returned with the appropriate type of value, 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, can use C + + template function to express "universal function"
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 argument type "field" we call 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 sumtest.cpp
[Root@localhost html]#./sumtest
SUM (float,float) 1 and 3=4
Looking at the code above, the C + + compiler generates a "float version" of the sum function and calls it. If we give a different parameter type, the compiler will make 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 sumtest.cpp
sumtest.cpp:In function ' int main () ':
Sumtest.cpp:10:no matching function for call to ' sum (float; int
&) '
Because the function template does not support two different types of parameter sums, the C + + compiler reports that a real function cannot be generated, giving the programmer the opportunity to know the invocation parameters in addition to the problem.
If you do not use a normal function with a template function, you may compile it even if the parameter type is not exactly the same. 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 sumtest.cpp
[Root@localhost html]#./sumtest1
SUM (float,int) 1 and 3=4
Because the int type can be automatically converted to float type in C + +, there is no error in this case.
A function template is not a real function, it is just a mold of the C + + compiler to generate a specific function. So you can't put the declaration and definition of a function template in separate files, and ordinary functions can do that.