Templates

With templates a class or function can be created that works with different data types.

Function Templates

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:

  • At lines 5 - 14 a template that returns the bigger of the 2 arguments is defined.
  • At line 21 the template function is called for integer arguments, line 26 - double, line 31 - char.
  • When chars are passed to the template, the chars arguments are compared by ascii code. Thus 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

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:

  • At 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.

Why using templates?

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: