With templates a class or function can be created that works with different data types.
The function template can work with different type of arguments.
Syntax for defining Template Function:
Syntax for calling Template Function:
Here's an example:
Output:
Explanation:
lines 5 - 14
a template that returns the bigger
of the 2 arguments is defined.line 21
the template function is called for
integer arguments, line 26
- double,
line 31
- char.z
is consider bigger than a
.
Line 33
is a bit more interesting. The arguments are of type
char but are defined as integer. So the char arguments are
converted to their ascii code.
Class templates can work with members of different types.
Syntax for defining class templates:
Syntax for creating class template object (via default constructor):
Example:
Output:
Explanation:
lines 39 - 41
are created 3 template class
object of 3 types (int, float, double).Lines 44, 47 and 50
call members of the class.They are suitable for larger apps are are flexible.
With them one code can be executed for different types of arguments / class members.
Instead of defining many functions with the same name and logic but different types of arguments, a template can be used.
A value swapping program:
Output:
The program above can be rewritten using templates like this:
Output: