I. Defining the MAX function template
// basics/mas.hpptemeplate<typename t>constConst const & b) { return a < b? b:a;}
Declaration of template Parameters
Template <comma-separated-list-of-paramaters>//temeplate< parameter list, separated by commas >
Another equivalent definition of template max ()
Temeplate <class t>const-Const const & B) { return a < b? b:a;}
Using templates
//Basics/max.cpp#include <iostream>#include<string>#include"max.hpp"intMain () {inti = the; Std::cout<<"Max (7,i):"<<::max (7, i) <<Std::endl; DoubleF1 =3.4; DoubleF2 =-6.7; Std::cout<<"Max (F1,F2):"<<::max (f1, F2) <<Std::endl; strings1="mathmatics"; stringS2="Math"; Std::cout<<"Max (S1,S2):"<<::max (S1, S2) <<Std::endl; }
The max () template is preceded by a domain qualifier::, to confirm that Max () is called in the global namespace.
Replacing a template parameter with a specific type is called instantiation. It produces an instance of a template, namely:
The first invocation of Max () instantiates the max template for int, just as with a separate declaration and implementation as follows
Const int int Const int const&);
C + + Templates learning process One