Templates

Template is a powerful feature in any language which enables us to write generic code. Generic code means that it enables us to define functions and classes that can work with different data types with same block of code / same logic. You do not need to write code for different data types explicitly. In this way, your code become reusable. Therefore, we can say that template is a feature in any language that give that particular language more flexibility.

For example, You are using a function that add two numbers and it is a template function. This function will operate for addition of any datatype. Like, sum(2, 3) will give 5 and sum(2.5, 2.1) will give 4.6. A single function is doin that. We do not need to define two separate sum functions for int and float.

Types of Templates

Templates are of two kinds in C++:

  1. Function Templates
  2. Class Templates

Function Templates

As we have discussed that function template is a function that is used with different data types.

In this example,

  • We have made a template using template keyword and then write our type name.
  • After type name, we write "T" - which is our generic data type.
  • Then we have written our function simply but changed our data type everywhere to "T".
  • Now whenever we call our template function, the data type "T" will be treated as the data type of the arguments. In this way, we can call our function with any data type we want.

Class Templates

Using class templates, we can define generic classes to work with different data types. Class templates are also defined using template keyword.

In this example,

  • We have made a class template using template keyword and then write our type name.
  • Now we are using two parameters, we write "T1" as first type name and "T2" as second type name - which are our generic data types.
  • Then we have written our class simply but changed our data types.
  • In main function, after our class name, we specified the data types of arguments we are passing.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min