Templates in C++ with Examples
Last Updated :
10 Jan, 2025
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the datatype as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by the keyword ‘class’.
How Do Templates Work?
Templates are expanded at compiler time. This is like macros. The difference is, that the compiler does type-checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class.

Function Templates
We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray().
To know more about the topic refer to Generics in C++.
Example:
C++
// C++ Program to demonstrate
// Use of template
#include <iostream>
using namespace std;
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
Example: Implementing Bubble Sort using templates in C++
C++
// C++ Program to implement
// Bubble sort
// using template function
#include <iostream>
using namespace std;
// A template function to implement bubble sort.
// We can use this for any data type that supports
// comparison operator < and swap works for it.
template <class T> void bubbleSort(T a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = n - 1; i < j; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
// Driver Code
int main()
{
int a[5] = { 10, 50, 30, 40, 20 };
int n = sizeof(a) / sizeof(a[0]);
// calls template function
bubbleSort<int>(a, n);
cout << " Sorted array : ";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
Output Sorted array : 10 20 30 40 50
Class Templates
Class templates like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
Example:
C++
// C++ Program to implement
// template Array class
#include <iostream>
using namespace std;
template <typename T> class Array {
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T> Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T> void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Can there be more than one argument for templates?
Yes, like normal parameters, we can pass more than one data type as arguments to templates. The following example demonstrates the same.
Example:
C++
// C++ Program to implement
// Use of template
#include <iostream>
using namespace std;
template <class T, class U> class A {
T x;
U y;
public:
A() { cout << "Constructor Called" << endl; }
};
int main()
{
A<char, char> a;
A<int, double> b;
return 0;
}
OutputConstructor Called
Constructor Called
Can we specify a default value for template arguments?
Yes, like normal parameters, we can specify default arguments to templates. The following example demonstrates the same.
Example:
C++
// C++ Program to implement
// Use of template
#include <iostream>
using namespace std;
template <class T, class U = char> class A {
public:
T x;
U y;
A() { cout << "Constructor Called" << endl; }
};
int main()
{
// This will call A<char, char>
A<char> a;
return 0;
}
What is the difference between function overloading and templates?
Both function overloading and templates are examples of polymorphism features of OOP. Function overloading is used when multiple functions do quite similar (not identical) operations, templates are used when multiple functions do identical operations.
What happens when there is a static member in a template class/function?
Each instance of a template contains its own static variable. See Templates and Static variables for more details.
What is template specialization?
Template specialization allows us to have different codes for a particular data type. See Template Specialization for more details.
Can we pass non-type parameters to templates?
We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of a template. The important thing to note about non-type parameters is, that they must be const. The compiler must know the value of non-type parameters at compile time. Because the compiler needs to create functions/classes for a specified non-type value at compile time. In the below program, if we replace 10000 or 256 with a variable, we get a compiler error.
Example:
C++
// C++ program to demonstrate
// working of non-type parameters
// to templates in C++
#include <iostream>
using namespace std;
template <class T, int max> int arrMin(T arr[], int n)
{
int m = max;
for (int i = 0; i < n; i++)
if (arr[i] < m)
m = arr[i];
return m;
}
int main()
{
int arr1[] = { 10, 20, 15, 12 };
int n1 = sizeof(arr1) / sizeof(arr1[0]);
char arr2[] = { 1, 2, 3 };
int n2 = sizeof(arr2) / sizeof(arr2[0]);
// Second template parameter
// to arrMin must be a
// constant
cout << arrMin<int, 10000>(arr1, n1) << endl;
cout << arrMin<char, 256>(arr2, n2);
return 0;
}
Here is an example of a C++ program to show different data types using a constructor and template. We will perform a few actions
- passing character value by creating an object in the main() function.
- passing integer value by creating an object in the main() function.
- passing float value by creating an object in the main() function.
Example:
C++
// C++ program to show different data types using a
// constructor and template.
#include <iostream>
using namespace std;
// defining a class template
template <class T> class info {
public:
// constructor of type template
info(T A)
{
cout << "\n"
<< "A = " << A
<< " size of data in bytes:" << sizeof(A);
}
// end of info()
}; // end of class
// Main Function
int main()
{
// clrscr();
// passing character value by creating an objects
info<char> p('x');
// passing integer value by creating an object
info<int> q(22);
// passing float value by creating an object
info<float> r(2.25);
return 0;
}
OutputA = x size of data in bytes:1
A = 22 size of data in bytes:4
A = 2.25 size of data in bytes:4
Template Argument Deduction
Template argument deduction automatically deduces the data type of the argument passed to the class or function templates. This allows us to instantiate the template without explicitly specifying the data type.
For example, consider the below function template to multiply two numbers:
template <typename t>
t multiply (t num1,t num2) { return num1*num2; }
In general, when we want to use the multiply() function for integers, we have to call it like this:
multiply<int> (25, 5);
But we can also call it:
multiply(23, 5);
We don’t explicitly specify the type ie 1,3 are integers.
The same is true for the template classes(since C++17 only). Suppose we define the template class as:
template<typename t>
class student{
private:
t total_marks;
public:
student(t x) : total_marks(x) {}
};
If we want to create an instance of this class, we can use any of the following syntax:
student<int> stu1(23);
or
student stu2(24);
Note: It is important to note that the template argument deduction for classes is only available since C++17, so if we try to use the auto template argument deduction for a class in previous version, it will throw an error.
Example of Template Argument Deduction
The below example demonstrates how the STL vector class template deduces the data type without being explicitly specified.
C++
// C++ Program to illustrate template arguments deduction in
// STL
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// creating a vector<float> object without specifying
// type
vector v1{ 1.1, 2.0, 3.9, 4.909 };
cout << "Elements of v1 : ";
for (auto i : v1) {
cout << i << " ";
}
// creating a vector<int> object without specifying type
vector v2{ 1, 2, 3, 4 };
cout << endl << "Elements of v2 : ";
for (auto i : v2) {
cout << i << " ";
}
}
Output
Elements of v1 : 1.1 2 3.9 4.909
Elements of v2 : 1 2 3 4
Note: The above program will fail compilation in C++14 and below compiler since class template arguments deduction was added in C++17.
Function Template Arguments Deduction
Function template argument deduction has been part of C++ since the C++98 standard. We can skip declaring the type of arguments we want to pass to the function template and the compiler will automatically deduce the type using the arguments we passed in the function call.
Example: In the following example, we demonstrate how functions in C++ automatically deduce their type by themselves.
C++
// C++ program to illustrate the function template argument
// deduction
#include <iostream>
using namespace std;
// defining function template
template <typename t> t multiply(t first, t second)
{
return first * second;
}
// driver code
int main()
{
auto result = multiply(10, 20);
std::cout << "Multiplication OF 10 and 20: " << result
<< std::endl;
return 0;
}
OutputMultiplication OF 10 and 20: 200
Note: For the function templates which is having the same type for the arguments like template<typename t> void function(t a1, t a2){}, we cannot pass arguments of different types.
Class Template Arguments Deduction (C++17 Onwards)
The class template argument deduction was added in C++17 and has since been part of the language. It allows us to create the class template instances without explicitly definition the types just like function templates.
Example: In the following example, we demonstrate how the compiler automatically class templates in C++.
C++
// C++ Program to implement Class Template Arguments
// Deduction
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
// Defining class template
template <typename T> class student {
private:
string student_name;
T total_marks;
public:
// Parameterized constructor
student(string n, T m)
: student_name(n)
, total_marks(m)
{
}
void getinfo()
{
// printing the details of the student
cout << "STUDENT NAME: " << student_name << endl;
cout << "TOTAL MARKS: " << total_marks << endl;
cout << "Type ID: " << typeid(total_marks).name()
<< endl;
}
};
int main()
{
student s1("Vipul", 100); // Deduces student<int>
student s2("Yash", 98.5); // Deduces student<double>
s1.getinfo();
s2.getinfo();
return 0;
}
Output
STUDENT NAME: Vipul
TOTAL MARKS: 100
Type ID: i
STUDENT NAME: Yash
TOTAL MARKS: 98.5
Type ID: d
Here, i means int, and d means double.
For template metaprogramming, refer to the following article – Template Metaprogramming.
Take a Quiz on Templates. Java also supports these features. Java calls it generics.
Similar Reads
C++ Tutorial | Learn C++ Programming
C++ is a middle-level programming language that was developed as an extension of the C programming language. In the early 1980s, Bell Labs was an enhancement of the C language to provide support for OOPs (Object Oriented Programming Systems) and additional features. When you look for the successor o
7 min read
Setting up C++ Development Environment
C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Writing First C++ Program - Hello World Example
The "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that is used to demonstrate how the coding process works. All you have to do is display the message "Hello World" on the
3 min read
C++ Variables
In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution. In this article, we will learn about the variables in C++ and how to use them in our programs. Let's take a look at
4 min read
C++ Data Types
Data types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory. C++ supports a wide variety of data ty
6 min read
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
9 min read
Basic Input / Output in C++
In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams. Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of byte
5 min read
Decision Making in C++
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a s
11 min read
C++ if Statement
The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int
3 min read
C++ if else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
4 min read
C++ if else if Ladder
In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
C++ Nested if-else Statement
Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels. Let's ta
3 min read
Switch Statement in C++
In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e
6 min read
Jump statements in C++
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function. In C++, there is four jump statement: Table of Content continue Statementbreak Statementreturn Statementgot
4 min read
C++ Loops
C++ Loops
In C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown. [GFGTABS] C++ #include <iostream> using namesp
7 min read
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand. Let's take a look at an example: [GFGTABS] C++ #include <bit
6 min read
C++ While Loop
In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while Loop
In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
Range-Based for Loop in C++
In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops. Let's take
3 min read
Functions in C++
A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.In s
15+ min read