If you compare two different types of values, you might write out the following code:
int Compare (conststringconststring &v2) { if (V1 < v2) { return -1; } if (V2 < v1) { return1; } return 0 ;}
int Compare (constdoubleconstdouble &v2) { if (V1 < v2) { return -1; } if (V1 > v2) { return1; } return 0 ;}
These two functions are not the same as the numerical comparison class, the function body is the same, and rewrite the trouble.
We need the template now.
Template <typename t>int Compare (constconst T &v2) { if ( V1 < v2) { return -1; } if (V1 > v2) { return1; } return 0 ;}
It can be done with a function body, which is called a generic function template.
1. Definition
The template definition starts with a keyword, followed by the templates parameter list, which is a comma-delimited list of one or more stencil parameters, wrapped with less than < and greater than sign >.
2. Instantiation
When the template is defined, the call is instantiated.
cout << Compare (12) << Endl; // Compare (const int &V1, const int &v2)
Because the compiler encounters a template definition, it does not generate code. The compiler generates code only when you instantiate a specific version of the template. This feature affects how we organize the code and when the error is detected.
C + + function templates