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.

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

FAQ's

What is a template function in C++?

A C++ template function 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.

What does an undefined reference to a function mean C++?

If you get the error of undefined reference to template function, it is because you have defined the template function in a cpp file and not a header file. In order to fix this error, you must implement template functions inside the header file.

What is generic function template in c++?

Generic functions use the concept of a C++ function template where it can support various types of data.

How do you define a function in a template class?

C++ 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.