Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App

Templates in C++

Last Updated : 15 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.

For example, same sorting algorithm can work for different type, so rather than writing and maintaining multiple codes, we can write one sort() and pass the datatype as a parameter.

Define Templates

Templates can be defined using the keywords "template" and "typename" as shown:

C++
template <typename A, typename B, ...> entity_definition 

The template keyword is used to define that the given entity is a template and typename keyword is used to define template parameters which are nothing but types that will be provided when an instance is created. The keyword typename can be replaced by keyword class anytime.

C++
template <class A, class B, ...> entity_definition 

The above syntax can define templates for three components (entities) of C++ language:

  • Function Templates
  • Class Templates
  • Variable Templates (Since C++ 14)

Create Template Instance

After definition, we can create the instance of template for any desired type by passing the type as template parameter as shown:

C++
name_of_entity<type1, type2, ...> 

The type1 will be substituted by the typename A in the definition, type2 will be substituted in place of typename B and so on.

Function Templates

In C++, templates allow us to write generic code for functions that can be used with different data types, and this can be achieved by function templates. For example, we can write a function that gives you the maximum of two numbers, but it can accept any number whether it is int, float, or double.

C++
#include <iostream> using namespace std;  // Function template definition 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');      return 0; } 

Output
7 7 g 

Class Templates

Class templates like function templates, are useful when a class defines something that is independent of the data type. It is useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.

Example:

C++
#include <iostream> using namespace std;  // Defining class template template <typename T> class Geek {   public:     T x;     T y;      // Constructor     Geek(T val1, T val2) : x(val1), y(val2) {}      // Method to get values     void getValues() {         cout << x << " " << y;     } };  int main() {      // Creating objects of Geek with     // different data types     Geek<int> intGeek(10, 20);     Geek<double> doubleGeek(3.14, 6.28);      // Access the templates values     intGeek.getValues();     cout << endl;     doubleGeek.getValues();      return 0; } 

Output
10 20 3.14 6.28

We can pass more than one data type as arguments to templates.

Example:

C++
#include <iostream> using namespace std;  // Defining class template with // multiple type parameters template <typename T1, typename T2, typename T3> class Geek {   public:     T1 x;     T2 y;     T3 z;      // Constructor to initialization     Geek(T1 val1, T2 val2, T3 val3) :         x(val1), y(val2), z(val3) {}      // Method to get values     void getValues() {         cout << x << " " << y << " " << z;     } };  int main() {      // Creating objects of Geek     // with different data types     Geek<int, double, string> intDoubleStringGeek(10, 3.14, "Hello");     Geek<char, float, bool> charFloatBoolGeek('A', 5.67f, true);      intDoubleStringGeek.getValues();     cout << endl;     charFloatBoolGeek.getValues();      return 0; } 

Output
10 3.14 Hello A 5.67 1

Template Variables (Since C++ 14)

A template variable is a variable that can work with any type specified when the variable is used, similar to how we use templates for functions or classes.

Syntax:

C++
template <typename T> constexpr T pi = T(3.14159); 

In the above statement, pi is the template variable. We use constexpr with the template variable because it ensures that the variable is a constant expression and is evaluated at compile time rather than at runtime.

Example:

C++
#include <iostream> using namespace std;  // Template variable with constexpr template <typename T> constexpr T pi = T(3.14159);  int main() {     // Using pi with different types     cout << "Pi as float: " << pi<float> << endl;     cout << "Pi as double: " << pi<double>;     return 0; } 

Output
Pi as float: 3.14159 Pi as double: 3.14159

Default Template Arguments

Like normal parameters, we can also specify default type arguments to templates. 

Example:

C++
#include <iostream> using namespace std;  // Defining class template with // multiple type parameters and one default type template <typename T1, typename T2 = double, typename T3 = string> class Geek {   public:     T1 x;     T2 y;     T3 z;      // Constructor to initialize data members     Geek(T1 val1, T2 val2, T3 val3) :     x(val1), y(val2), z(val3) { }      // Method to get values     void getValues() {         cout << x << " " << y << " " << z;     } };  int main() {      // Creating objects of Geek     // with different data types     Geek<int, float, string> intFloatStringGeek(10, 5.67f, "Hello");     Geek<char> charDoubleStringGeek('A', 3.14, "World");      intFloatStringGeek.getValues();     cout << endl;     charDoubleStringGeek.getValues();      return 0; } 

Output
10 5.67 Hello A 3.14 World

Working of Templates

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.

Template Specialization

In C++, template specialization allows us to define different implementations of a template for specific data types or combinations of data types.

Example:

C++
#include <bits/stdc++.h> using namespace std;  // Generic template template <typename T> void print(T value) {     cout << value; }  // Template specialization for int template <> void print(int value) {     cout << "Value: " << value; }  int main() {     print(3);     return 0; } 

Output
Value: 3

Template Non-Type Arguments

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 of value at compile time.

Example:

C++
#include <iostream> using namespace std;  // Second argument of template is // not template type 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; } 

Output
10 1

Template Argument Deduction

Template argument deduction automatically deduces the data type of the argument passed to the templates. This allows us to instantiate the template without explicitly specifying the data type.

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:

The below example demonstrates how the STL max() method deduces the data type without being explicitly specified.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     cout << max(3, 4);     return 0; } 

Output
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:

C++
#include <iostream> using namespace std;  template <typename t> t multiply(t first, t second) {     return first * second; }  int main() {     cout << multiply(3, 4);     return 0; } 

Output
12

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:

C++
#include <iostream> using namespace std;  template <typename T> class Geek {   public:     T x;     T y;     Geek(T val1, T val2) : x(val1), y(val2)     {     }     void getValues()     {         cout << x << " " << y;     } };  int main() {      // Class template argument deduction     Geek intGeek(10, 20);     Geek doubleGeek(3.14, 6.28);     intGeek.getValues();     cout << endl;     doubleGeek.getValues();     return 0; } 


Output

10 20
3.14 6.28

Template Metaprogramming

In C++, template metaprogramming refers to template perform computation at the compile time rather than runtime. To perform computation at compile time, template metaprogramming involves recursive template structures where templates call other templates during compilation.

Example:

C++
#include <iostream> using namespace std;  // Template metaprogramming for // calculating factorial at compile-time template <int N> struct Factorial {     static const int value = N * Factorial<N - 1>::value; };  // Specialization for the // base case (Factorial<0>) template <> struct Factorial<0> {     static const int value = 1; };  int main() {     // Factorial computation     // happens at compile-time     cout << "Factorial of 5 is: " << Factorial<5>::value;     return 0; } 

Output
Factorial of 5 is: 120

Variadic Templates

If you notice carefully, the number of parameters in regular templates is fixed. However, with variadic templates, we can pass any number of parameters to the templates.

Example:

C++
#include <iostream> using namespace std;  // Base case: when no // arguments are left int sum() {     return 0; }  // Recursive case: sum the // first argument and recursively // sum the rest template <typename T, typename... Args> T sum(T first, Args... args) {      // Recursive call with     // remaining argument     return first + sum(args...); }  int main() {     cout << "Sum of 1, 2, 3: " << sum(1, 2, 3) << endl;     cout << "Sum of 4, 5: " << sum(4, 5);     return 0; } 

Output
Sum of 1, 2, 3: 6 Sum of 4, 5: 9

Templates vs Function Overloading

Differences between templates and function overloading are shown below:

Function OverloadingFunction Templates
Function overloading allows multiple functions with the same name but different parameters (number or types).Function templates define a generic function that works with any data type.
Different functions with the same name must have different parameter types, number of parameters, or both.A single template function can work with any data type by using type parameters.
Each overloaded function is explicitly defined for specific types.A function template is defined once and can be used for multiple types.
Requires writing separate functions for each type.No code duplication, as the same template is used for various types.
Used when you need to perform the same task on different data types, but with different implementations.Used when the same function logic applies to different types, and type is deduced or explicitly provided.

K

kartik
Improve
Article Tags :
  • C++
  • cpp-template
Practice Tags :
  • CPP

Similar Reads

    C++ Tutorial | Learn C++ Programming
    C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
    5 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 demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
    4 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.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
    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 typ
    7 min read
    Operators in C++
    C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
    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 bytes
    5 min read

    Decision Making in C++

    Decision Making in C (if , if..else, Nested if, if-else-if )
    In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
    7 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:C++#include <iostream> using namespace std; int main() { 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
    3 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 tak
    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
    5 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 Contentcontinue Statementbreak Statementreturn Statementgoto S
    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.C++#include <iostream> using namespace std; int
    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:C++#include <bits/stdc++.h
    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 building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences