Templates in C++

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
By Prateek Narang
Free
star5
Enrolled: 1000
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
Prateek Narang
Free
5
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

The templates are one of the most powerful and widely used methods added to C++, which allows us to write generic programs. Templates in C++ allow us to define generic functions and classes. Templates in C++ promote generic programming, meaning the programmer does not need to write the same function or method for different parameters.

The idea behind the templates in C++ is very simple. We pass the data type as a parameter, so we don’t need to write the same code for different data types.

Scope of the Article

The article contains topics such as

  • What are templates in C++, and the implementation of templates in C++?
  • What are the advantages and disadvantages of templates in C++?
  • What are the types of templates in C++?
  • What are the function templates and class templates in C++?
  • What do we mean by overloading Template Function in C++, and what is the difference between function overloading and templates in C++?
  • Difference between typename and class keyword.

Each of the topics is explained clearly with diagrams and examples wherever necessary.

Introduction to Templates in C++

The templates are one of the most powerful and widely used methods added to C++, allowing us to write generic programs. Templates in C++ allow us to define generic functions and classes. Templates in C++ promote generic programming, meaning the programmer does not need to write the same function or method for different parameters.

We can define a template as a blueprint for creating generic classes and functions. The idea behind the templates in C++ is straightforward. We pass the data type as a parameter, so we don’t need to write the same code for different data types. Refer to the image below for better visualization.

Introduction to Templates in C++

We use two keywords - template and typename in templates in C++ to achieve generic programming.

Note: The typename keyword can always be replaced by the keyword class.

Some of the most common examples of templates in C++ can be:

  • Library containers like iterators. We can define iterators of different data types by passing the data type as a parameter to the iterator.
  • Sorting algorithms defined for STL in C++. We can have the data sorted in an order irrespective of the data type.

Examples of templates in C++:

  • vector <int> vec;
  • vector <char> vec;
  • stack <string> s;
  • queue <int> q; etc.

How To Use Templates/Implementation?

As seen in the previous section, we use templates in C++ to create generic methods and classes. Templates in C++ get expanded at compile time, just like any macros (example #define PI 3.14), and allow a function or class to work on different data types without being rewritten.

Refer to the image below to see the compile-time working of templates in C++.

compile-time working of templates in C++

To use templates in C++, we need to use the two keywords - template and typename. We should first write the keyword template which tells the compiler that the current function or class is a blueprint or template. After writing the template, we mention the keyword typename and a placeholder name (T) for a data type used by the function or class.

Templates in C++ can be implemented in two ways, i.e., Function Templates and Class Templates. Refer to the next section for a detailed explanation and implementation.

Types of Templates in C++

As we know, we can use templates in C++ to define generic functions and classes. We can represent templates in C++ in two different ways, namely - function templates and class templates. Let us learn about both representations in detail.

1. Function Templates

Function templates are similar to normal functions. Normal C++ functions work with only one data type, but a function template code can work on multiple data types. Hence, we can define function templates in C++ as a single generic function that can work with multiple data types.

Note: We can also overload a standard function to work on various data types.

Functional templates are more powerful than overloading a normal function as we need to write only one program, which can work on all data types.

Syntax of the template function:

In the syntax above:

  • T is the type of argument or placeholder that can accept various data types.
  • class is a keyword used to specify a generic type in a template declaration. As we have seen earlier, we can always write typename in the place of class.

Some of the pre-defined examples of function templates in C++ are sort(), max(), min(), etc. Let’s take an example to understand the working and syntax of function templates in C++.

Example:

Output:

In the example above, we have defined a template function, namely add(). We can provide multiple data types as arguments for the function.

2. Class Templates

Just like the function templates in C++, we can also use class templates to create a single class that can work with the various data types. Just like function templates, class templates in C++ can make our code shorter and more manageable.

Syntax of the template function:

In the syntax above:

  • T is a placeholder template argument for the data type. T or type of argument will be specified when a class is instantiated.
  • class is a keyword used to specify a generic type in a template declaration.

Note: When a class uses the concept of template in C++, then the class is known as a generic class.

Some pre-defined examples of class templates in C++ are LinkedList, Stack, Queue, Array, etc. Let’s take an example to understand the working and syntax of class templates in C++.

Example:

Output:

In the example above, we have defined a template class (Test) that returns the number of various data types. We have a return type T, meaning they can be of any type.

Overloading of Template Function in C++

Overloading is the feature that allows the specification of more than one function of the same name in the same scope.

So, by overloading template functions in C++, we can define function templates in C++ having the same name but called with different arguments.

Let us take an example to understand the overloading of the Template Function in C++.

Output:

In the example above, we have defined a template function named display(), which takes one argument and performs the instruction written inside it. We have also overridden the display() function with an integer argument. So, when we provide an integer value as a parameter to the function, an overloaded function (i.e., display(int t)) will be called rather than the template function. The template display method will be called for the rest of the data types, i.e., display(T t1).

Difference between Function Overloading and Templates in C++

Before learning about the difference between function overloading and templates in C++, we should first know what polymorphism is in C++.

Polymorphism means having many forms. Polymorphism is an important concept of Object-Oriented Programming. We can define polymorphism as the ability of a function or message to be displayed in more than one form.

Both function overloading and templates in C++ are examples of polymorphism in C++. We should use functional overloading when we need to define multiple functions performing similar operations. On the other hand, we should use templates in C++ when we need to define multiple functions performing identical operations.

One of the most important differences between function overloading and templates in C++ is that templates cannot take a varying number of arguments, but an overloaded function can take a varying number of arguments.

typename VS class keyword

The typename and class are keywords used in templates in C++. There is no difference between the typename and class keywords. Both of the keywords are interchangeably used by the C++ developers as per their preference. There is no semantic difference between class and typename in a type-parameter-key.

There is a special scenario or case where we cannot use typename at the place of class. When declaring a template of a template parameter, we must use class. Refer to the syntax below for a better understanding.

Invalid Usage:

Valid Usage:

Advantages of Using Templates in C++

As we have seen the working, use cases, and examples of templates in C++, let us now learn some of the advantages and disadvantages of templates in C++. Let us first know the advantages of templates in C++. Disadvantages are discussed in the next section.

  • Templates in C++ remove code duplication.
  • Templates in C++ are evaluated at run-time just like macros; hence they are faster than normal functions.
  • Templates in C++ help us to make generic callbacks.
  • Templates in C++ help us to build type-safe code.
  • Templates in C++ can be used as an alternative to operator overloading.
  • Templates in C++ help us improve performance as we need not write the same class, function, or code for various data types.
  • Templates in C++ help us to write very efficient and powerful libraries. Example: STL in C++.

Disadvantages of Using Templates in C++

In the earlier section, we have learned about the advantages of templates in C++. Templates in C++ have very few disadvantages. Let us now discuss some of the disadvantages of using templates in C++.

  • Templates in C++ make the language much more complicated, and it is also difficult to implement.
  • Some of the C++ compilers exhibit poor support for templates in C++.
  • Template errors can only be detected by the compiler when the template is instantiated.
  • As templates are calculated at compile time rather than run time when template functions or classes are large and complicated, they can slow the compile time.
  • Templates in C++ cannot be handled correctly by older C++ compilers.

Conclusion

  • The templates are one of the most powerful and widely used methods added to C++, which allows us to write generic programs. Templates in C++ allow us to define generic functions and classes.
  • To use templates in C++, we use the two keywords - template and typename. We can also use the class keyword in the place of typename.
  • Templates in C++ remove code duplication and help us to make generic callbacks.
  • Templates in C++ help us to write very efficient and powerful libraries. Example: STL in C++.
  • Templates in C++ get expanded at compiler time, just like any macros.
  • Function templates are similar to normal functions. Function templates in C++ are single generic functions that can work with multiple data types.
  • Just like the function templates in C++, we can also use class templates to create a single class that can work with the various data types.
  • As templates are calculated at compile time rather than run time when template functions or classes are large and complicated, they can slow the compile time.