C++ Templates in plain English

What is a template?

C++ templates is a sophisticated feature in the C++ language which allows programmers to create generic functions and classes. By being able to use templates to create generic functions and classes, this allows us to use different data types which can be reused again in different code segments.

Function templates

A function template behaves like a normal C++ function but the advantage it has when a template is used is that it can support many different types of data. When the complier is running the code, it will create a different version for the function when there are different types of data being used. The code example of Function templates will explain this clearly.

Function templates code 1

Function templates code 2

Class Templates

Class Templates allows programmers to create a normal class which defines all the components used by that class but the actual data being manipulated will be specified by what kind of data is inside the parameter(brackets) of the class. This can be useful when you are implementing an algorithm like a linked list. When you are using integers for a linked list, a class template will allow you to work with a list of characters. Let’s look at some example code of a class template that is used for division program:

class template part 1

class template part 2

The most important concept to understand with templates

The main concept to understand with templates is that they can allow us to generate functions and classes which allow us to reuse different data types without being rewritten every time for each one.

Share this post