Templates in C++

In this tutorial we will study and understand the concept of Templates in C++ and its implementation to achieve Generic programming.

Templates in C++

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. Templates are powerful features of C++ which allows you to write generic programs.
A template is a blueprint or formula for creating a generic class or a function. In simple terms, you can create a single function or a class to work with different data types using templates.
Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs. The concept of templates can be used in two different ways:

  • Function Templates
  • Class Templates

 

Templates in C++

Function Templates in C++

The general form of a template function definition is shown here:

Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.

Example Program of Function Template in C++

Run Online

Output
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Templates in C++

Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:

Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.

Example Program of Class Template in C++

Run Online

Output
Total Objects: 1
100
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *