We just learned about function overloading , which can handle multiple data types. Although they have the same name, they still need to be defined separately. It would be great if the code can be streamlined and templated! To this end, C++ provides a function template mechanism, which greatly improves the reusability of code.
Function template allows you to create a general function that supports multiple formal parameters. Use the keyword template to define it in the following form:
template<class type name 1, class type name 2...> return value function name (formal parameter list column) template parameter list {function body}
To explain, in this general form, the template in the first line <class type name 1, class type name 2...> is a declaration statement . template is the keyword that defines the template function. There can be multiple types in the angle brackets. The preceding ones are Use class (or typename to define). Then follow it with the defined function template. Remember not to add other statements in the middle, otherwise an error will be reported!
Below, let’s take a look at a specific example!
#include<iostream>usingnamespacestd;template<classT1,classT2>T1add(T1x,T2y){cout<<sizeof(T1)<<,<<sizeof(T2)<<t;returnx+y;}intmain(){ cout<<add(10,20)<<endl;;cout<<add(3.14,5.98)<<endl;cout<<add('A',2)<<endl;return0;}
The above is a template for an addition function. You can see that we have defined an add function template, and the variable types in it are replaced by T1 and T2.
In the main function, when we actually call it, we call it three times, passing in three different types. The T1 and T2 types in the template function will be changed into specific types according to the actual type passed in. This transformation is called an instance of the template. change.
Then we run the program and we can see what types T1 and T2 are called each time, how many bytes they are, and the summation result. The running effect is as follows:
You can understand the code line by line and complete the experiment by yourself.