What is a c++ template?
C++ template is a sophisticated feature in the C++ language which allows programmers to create generic functions and classes. Being able to use a template to create generic functions and classes, 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 compiler 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.
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:
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.