C++ Templates


What are Templates?

  • Template is an important and powerful feature in C++. It is used to pass the data type as a parameter so that you don’t need to write same code for different data types.
  • It allows you to define the generic classes and generic functions and thus provides support for generic programming.
  • For example if you need to sort( ) for different data type rather than writing and maintaining the multiple codes you can write one sort( ) and pass data type as a parameter.

How Templates work?

  • The templates are expanded at the compiler time and they are like macros. The difference is that compiler does type checking before template expansion.
  • The source code contains only function or class but compiled code may contain multiple copies of same function or class.

Types of Template

Let us discuss these two in details:

Function Templates:

The function template can work with different data types at once. The concept of function template is used by generic functions and it defines a set of operations that can be applied to the various types of data. The type of the data that the function will operate on depends on the type of the data passed as a parameter. Syntax of function template:

Let us have a look at the example:

Class Templates:

  • The class templates can be defined in the same way as functions are defined and when the class uses the concept of template then that class is known as generic class.
  • The class template can be useful for classes like linked list, stack, array, etc.

Syntax of class template:

Let us have a look at the example:


Like it? Please Spread the word!