How to write a function template
A function template should be written at the beginning of the program in the global area, or you may place it into a header file. All function templates begin with a template declaration.
The syntax is :
- The C++ keyword template
- A left angle bracket ( < )
- A comma separates a list of generic types, each one. A generic type having of two parts
1. the keyword class ( this usage of class has nothing to do with the key word class used to make user-defined type.)
2. a variable that shows some generic type, and will be used whenever this type requires to be written in the function definition. Typically the name T is used, but any valid C++ name will do.
- A right angle bracket ( > ).
e.g.
template < class T>
T max(char x, char y)
{
return ( x > y) ? x : y ;
}
void main()
{
cout << max( 1,2) << endl;
cout << max( 5.62,3.48) << endl;
cout << max('A','a') << endl;
cout << max( 4,3) << endl;
}
The output is :
2
5.62
a
6