function Template:
definition: A function template is not a real function, and the compiler cannot generate executable code for it. Defining a function template is just a description of the function's functional framework, and when it executes, it determines its functionality based on the actual parameters passed.
Format: template <class type parameter 1,class type parameter 2,...>
Example:
Template <class t>t Inc (t N) { return1 + N;}
? do not instantiate a function template by argument
cout << inc<double> (4)/ 2; // output: 2.5
?
function templates can be overloaded as long as their formal parameter lists or type argument tables are different . ?
Order of function templates and functions in cases where multiple functions and function templates have the same name, the compiler processes a function call statement as follows:1) First find the normal function (which is not instantiated by the template) that matches the parameters exactly. 2) Then find the template function that exactly matches the parameters. 3) The common function that can be matched after the automatic type conversion is found. 4) The above can not be found, the error
Template <classT>T Max (t A, T b) {cout<<"Templatemax"<<Endl; return 0;} Template<classTclassT2>T Max (t A, T2 b) {cout<<"TemplateMax2"<<Endl; return 0;}DoubleMax (DoubleADoubleb) {cout<<"Mymax"<<Endl; return 0;}intMainvoid){ intI=4, j=5; Max (1.2,3.4);//Output:mymaxMax (I,J);//Output:templatemaxMax (1.2,3);//Output:templatemax2 return 0;}
? No type auto-conversions when matching function templates
Template <class t>t myFunction (t arg1, t arg2) { << arg1 <<"" << arg2 << Endl; return Arg1;} ... myFunction (5,8.5); // Error, no matching function for call to ' myFunction (int, double) '
? Example of a function template: Map
The implementation converts a specified sequence of an array into another array by a custom type conversion rule.
1#include <iostream>2 using namespacestd;3Template <classTclassPred>4 voidMap (t S, T E, T X, Pred op) {5 for(; s! = e; ++s, + +)x) {6*x = OP (*s);7 }8 }9 DoubleSquare (Doublex) {Ten returnx*x; One } A intMainvoid) { - inta[5] = {1,2,3,4,5}, b[5]; -Map (A, A +5, B, Square); the for(intI=0; i<5; i++) { -cout << B[i] <<ends; - } - return 0; +}
Execute Map (A, a+5, B, Square) , and then instantiate the following function:
void Map (int * s, int * e, int * x, double (*op) (double)) {
for (; s! = e; ++s, ++x) {
*x = OP (*s);
}
}
The element in a[] is squared back into b[].
2018-01-24
Introduction to C + + function templates