The Wayback Machine - https://web.archive.org/web/20240828165003/https://www.geeksforgeeks.org/templates-cpp/
Open In App

Templates in C++ with Examples

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

templates-cpp

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;
}

Output
7
7
g

 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;
}

Output
 1 2 3 4 5

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;
}

Output
Constructor 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;
}

Output
Constructor Called

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 25 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;
}

Output
10
1

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;
}

Output
A = 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;
}

Output
Multiplication 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.



Previous Article
Next Article

Similar Reads

not1 and not2 function templates in C++ STL with Examples
These are functions which takes unary and binary function object(functors) and returns complement of that function objects. It can be usable in competitive programming to get complement of binary and unary functions. These functions are very useful when writing code for complement function is harder or lengthy. For example, if we want to delete con
3 min read
Implementing Stack Using Class Templates in C++
The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). The simple idea is to pa
5 min read
Abbreviated Function Templates in C++ 20
Abbreviated Function Template is a new feature introduced in C++20 to simplify the syntax of function template definition. Traditionally, we use function templates to define a function that can take parameters of different types. But sometimes, it might get complicated and hard to understand. In these cases, we can implement an abbreviated function
3 min read
C++ Variable Templates
Over the years C++ has undergone advancements to improve its capabilities and coding efficiency. One notable addition in C++14 is the introduction of variable templates. These variable templates allow you to create a group of variables or static data members that can be customized providing flexibility for your code. Variable TemplatesVariable temp
4 min read
Why can templates only be implemented in the header file?
Templates are a powerful feature in C++ that allows for the creation of generic functions and classes. They provide a way to write code that works with different data types without sacrificing type safety. However, one notable restriction when working with templates is that their implementation is often required to be in the header file. This limit
4 min read
Templates and Static variables in C++
Function templates and static variables: Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; void fu
2 min read
Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include&lt;iostream&gt; using namespace std; template&lt;class T, class U = char&gt; class A { public: T x; U y; }; int main() { A&lt;char
1 min read
Variadic function templates in C++
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with this feature for C+
3 min read
Templates in C++ vs Generics in Java
While building large-scale projects, we need the code to be compatible with any kind of data which is provided to it. That is the place where your written code stands above that of others. Here what we meant is to make the code you write be generic to any kind of data provided to the program regardless of its data type. This is where Generics in Ja
4 min read
wcscpy() function in C++ with Examples
The wcscpy() function is defined in cwchar.h header file. The wcscpy() function is used to copy a wide character string from source to destination. Syntax: wchar_t *wcscpy(wchar_t *dest, const wchar_t *src); Parameters: This method accepts the following two parameters: dest: specifies the pointer to the destination array. src: specifies the pointer
1 min read
wcscmp() function in C++ with Examples
The wcscmp() function is defined in cwchar.h header file. The wcscmp() function is used to compares two null terminating wide string and this comparison is done lexicographically. Syntax: int wcscmp(const wchar_t* str1, const wchar_t* str2); Parameters: This method takes the following two parameters: str1: This represents the pointer to the first s
2 min read
ratio_equal() in C++ with examples
The ratio_equal() is an inbuilt function in C++ STL that checks if two given ratios are equal or not. Syntax: template &lt; class ratio1_name, class ratio2_name &gt; ratio_equal Template Parameters: The function accepts two template parameters ratio1 and ratio2 which are to be compared. Return value: The function returns true if the ratios are equa
1 min read
quick_exit() function in C++ with Examples
The quick_exit() function is defined in the stdlib header file. The quick_exit() function is used for normal termination of a process without completely cleaning the resources. If val is zero or EXIT_SUCCESS, it shows successful termination of program.If the value is non-zero or EXIT_FAILURE, it shows that the program is not successfully terminated
1 min read
feclearexcept in C++ with Examples
feclearexcept() clears the supported floating-point exceptions represented by excepts. Syntax: int feclearexcept(int excepts); excepts : Bitmask listing of exception flags to clear Return value: The feclearexcept() function returns zero value if all the exceptions were cleared or if excepts is equal to zero. It returns nonzero if any error occurs.
1 min read
multiset lower_bound() in C++ STL with Examples
The multiset::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the first element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passe
3 min read
multiset upper_bound() in C++ STL with Examples
The multiset::upper_bound() is a built-in function in C++ STL that returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points an element which points to the position after the last element in the container. Sy
3 min read
multiset max_size() in C++ STL with Examples
The multiset::max_size() is a built-in function in C++ STL which returns the maximum number of elements a multiset container can hold. Syntax: multiset_name.max_size() Parameters: The function does not accept any parameters. Return Value: The function returns the maximum number of elements a multiset container can hold. Below programs illustrate th
1 min read
forward_list max_size() in C++ STL with Examples
The forward_list::max_size() is a built-in function in C++ STL which returns the maximum number of elements a forward_list container can hold Syntax: forward_list_name.max_size() Parameters: The function does not accept any parameters. Return Value: The function returns the maximum number of elements the container can hold. Below programs illustrat
1 min read
std::allocator() in C++ with Examples
Allocators are objects responsible for encapsulating memory management. std::allocator is used when you want to separate allocation and do construction in two steps. It is also used when separate destruction and deallocation is done in two steps. All the STL containers in C++ have a type parameter Allocator that is by default std::allocator. The de
3 min read
array data() in C++ STL with Examples
The array::data() is a built-in function in C++ STL which returns an pointer pointing to the first element in the array object. Syntax: array_name.data() Parameters: The function does not accept any parameters. Return Value: The function returns an pointer. Below programs illustrate the above function: Program 1: // CPP program to demonstrate the /
2 min read
multiset size() in C++ STL with Examples
The multiset::size() is a built-in function in C++ STL which returns the number of elements in the multiset container. Syntax: multiset_name.size() Parameters: The function does not accept any parameters. Return Value: The function returns the number of elements in the multiset container. Below programs illustrate the above function: Program 1: //
2 min read
ratio_not_equal() in C++ with examples
The ratio_not_equal is an inbuilt function in C++ STL that checks if two given ratios are not equal or equal. Syntax: template &lt; class ratio1_name, class ratio2_name &gt; ratio_not_equal Template Parameters: The function accepts two template parameters ratio1 and ratio2 which are to be compared. Return value: The function returns true if the rat
1 min read
std::bit_or in C++ with Examples
The bit_or is an inbuilt function in C++ which is used to perform bitwise_or and return the result after applying the bitwise_or operation on it's arguments. Header File: #include &lt;functional.h&gt; Template Class: template &lt;class T&gt; struct bit_or; Parameters: It accepts a parameter T which is the type of the argument to be compared by the
2 min read
iswprint() in C/C++ with Examples
The iswprint() is a built-in function in C/C++ which checks if the given wide character can be printed or not. It is defined within the cwctype header file of C++. By default, the following characters are printable: Digits (0 to 9)Uppercase letters (A to Z)Lowercase letters (a to z)Punctuation characters (!"#$%&amp;'()*+, -./:;?@[\]^_`{|}~)Space Sy
2 min read
iswgraph() in C/C++ with Examples
The iswgraph() is a built-in function in C/C++ which checks if the given wide character has a graphical representation or not. It is defined within the cwctype header file of C++. By default, the following characters are graphic: Digits (0 to 9)Uppercase letters (A to Z)Lowercase letters (a to z)Punctuation characters (!"#$%&amp;'()*+, -./:;?@[\]^_
2 min read
btowc() function in C/C++ with Examples
The btowc() is a built-in function in C/C++ which converts a character to its wide character equivalent. It is defined within the cwchar header file of C++. Syntax: wint_t btowc( int ch ); Parameter:The function accepts a single mandatory parameter ch which specifies the single byte character to convert to it's wide character. Return Value: The fun
2 min read
negative_binomial_distribution in C++ with Examples
This function is defined in header randomRandom. Negative binomial distribution is Random number distribution that produces integers according to a negative binomial discrete distribution (also known as Pascal distribution), which is described by the following probability mass function. [Tex]P(i|k, p) = \binom{k + i - 1}{i} \cdot p^k \cdot (1 - p)^
3 min read
mbrtoc16() in C/C++ with Examples
The mbrtoc16() is a built-in function in C/C++ which converts a narrow multibyte character to a 16 bit character representation. It is defined within the uchar.h header file of C++. Syntax: ssize_t mbrtoc16( char16_t* pc16, const char* s, size_t n, mbstate_t* ps); Parameters: The function accepts four mandatory parameter which are described below:
3 min read
mbrtoc32() in C/C++ with Examples
The mbrtoc32() is a built-in function in C/C++ which converts a narrow multibyte character to a 32 bit character representation. It is defined within the uchar.h header file of C++. Syntax: size_t mbrtoc32( char32_t* pc32, const char* s, size_t n, mbstate_t* ps); Parameters: The function accepts four mandatory parameter which are described below: s
3 min read
wmemset() in C/C++ with Examples
The wmemset() function is a builtin function in C/C++ which copies a single wide character for a specified number of time to a wide character array. It is defined within the cwchar header file in C++. Syntax: wmemset(des, ch, count) Parameters: The function accepts three parameters which are described below. des: It specifies to the wide character
2 min read
Article Tags :
Practice Tags :