C++ Templates

A C++ template is a powerful feature added to C++. It allows us to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for several data types .

Types of Templates

There are mainly two types of Templates in C++.

Now, we will discuss these templates one by one.

1) Function Template

In C++ , a function template enables us to write generic functions that function with any data type. Generic functions define a set of operations that can be applied to the various data types.

The data type that is used in the function is determined at compile-time. The function call is depending on the type of the data. Consider an example, the Quick Sort algorithm may be implemented using a function template. It enables the same sorting function to work with several arrays of integers, doubles, floats, and several other data types.

A generic function can be created using the keyword template. This keyword defines a template parameter, which acts as a placeholder for a data type.

Syntax of Function Template

It has the following syntax:

Example

template < class Ttype> 

ret_type func_name(parameter_list)  

{  

    // body of function.  

}

In this syntax,

  • Ttype: It is a placeholder name for a data type used by the function. It is used inside the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type.
  • class: A class keyword is used to specify a generic type in a template declaration.
  • C++ Function Template Example

Let us take an example to illustrate the function template in C++.

Example

Example

#include <iostream>  

using namespace std;    //using standard namespace

template<class T> T add(T &a,T &b)  

{  

    T result = a+b;  

    return result;  

      

}  

int main()    //Main Function

{  

  int i =2;  

  int j =3;  

  float m = 2.3;  

  float n = 1.2;  

  cout<<"Addition of i and j is : "<<add(i, j);  

  cout<<'\n';  

  cout<<"Addition of m and n is : "<<add(m, n);  

  return 0;  

}

Output:

Output

Addition of i and j is : 5

Addition of m and n is : 3.5

Explanation:

In the above example, we create the function template that can perform the addition operation on any type, whether it be integer, float, or double.

Function Templates with Multiple Parameters

In C++, we can use multiple generic types in the template function by using the comma to separate the list.

Syntax

It has the following syntax:

Example

template<class T1, class T2,.....>

return_type function_name (arguments of type T1, T2....)

{

    // body of function.

}

In this syntax, we have seen that the template function can accept any number of arguments of a different type.

C++ Function Templates with Multiple Parameters Example

Let us take an example to illustrate the function template with multiple parameters in C++.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

template<class X,class Y> 

void fun(X a,Y b)  

{  

    cout << "Value of a is: " <<a<< endl;  

    cout << "Value of b is: " <<b<< endl;  

}  

int main()   //main function

{  

   fun(15,12.3);  

   

   return 0;  

}/textarea></div>

			<a class="btn btn-apna" href="https://www.cpptutorial.com/cpp/tryit?program=cpp-templates2" target="_blank">Compile and Run</a></div>

			<p><strong>Output:</strong></p>

			<div class="codeblock3">

			<pre>Value of a is: 15

Value of b is: 12.3

</pre>

			</div>

<p><strong>Explanation:</strong></p>

<p>In this example, we have taken a function template with two generic types, X and Y, which allows the fun() function to accept arguments of different data types. When the fun(15, 12.3) is invoked, the compiler automatically generates a version of the function where X is int and Y is double, and it displays both values.</p>

<h3 class="h3">Function Overloading with Template</h3>

<p>In C++, we can overload the generic function. It means that the overloaded template functions can differ in the parameter list.</p>

<p><strong>C++ Overloading a Function Template Example</strong></p>

<p>Let us take an example to illustrate the overloading a function template in C++.</p>

			<div class="codewrapper">

			<h3 class="h3">Example</h3>

			<div class="codeblock"><textarea class="cpp" name="code">#include <iostream>  

using namespace std;   //using standard namespace

template<class X> 

void fun(X a)  

{  

    cout << "Value of a is : " <<a<< endl;  

}  

template<class X,class Y> void fun(X b ,Y c)  

{  

    cout << "Value of b is : " <<b<< endl;  

    cout << "Value of c is : " <<c<< endl;  

}  

int main()   //main function

{  

   fun(10);  

   fun(20,30.5);  

   return 0;  

}

Output:

Output

Value of a is : 10

Value of b is : 20

Value of c is : 30.5

Explanation:

In the above example, the template of the fun function is overloaded, where two versions of the fun function are defined. The first accepts a single generic parameter, and the other accepts two generic parameters of potentially different types. When the fun(10) is called, the single-parameter version is called, and when fun(20, 30.5) is called, the two-parameter version is used.

Restrictions of Function Templates

In C++, function templates cannot perform the same operation for all the versions of a function, especially when the functionality differs.

C++ Example of Restrictions of Function Template

Let us take an example to illustrate the restrictions of function templates in C++.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

void fun(double a)  

{  

    cout<<"value of a is : "<<a<<'\n';  

}  

  

void fun(int b)  

{  

    if(b%2==0)  

    {  

        cout<<"Number is even";  

    }  

    else  

    {  

        cout<<"Number is odd";  

    }  

  

}  

  

int main()   //main function

{  

   fun(4.6);  

   fun(6);  

   return 0;  

}

Output:

Output

value of a is : 4.6

Number is even

Explanation:

In this example, we overload the ordinary functions. We cannot overload the generic functions as both functions have different functionalities. The first one displays the value, and the second one determines whether the number is even or not.

2) Class Template

In C++, the class template can also be defined similarly to the function template. When a class uses the concept of a Template, the class is known as a generic class.

We can define a template for a class. For example, a class template can be created for the array class that can accept the array of various types, such as int array, float array, and double array.

Syntax

Example

template<class Ttype>

class class_name

{

  .

  .

}

In this syntax,

  • Ttype: It is a placeholder name that will be determined when the class is instantiated. We can define multiple generic data types using a comma-separated list. The Ttype can be used inside the class body.

Now, we create an instance of a class

Example

class_name<type> ob;

Where,

  • class_name: It represents the name of the class.
  • type: It represents the data type that the class is operating on.
  • ob: It represents the name of the object.
  • C++ Class Template Example

Let us take an example to illustrate the class template in C++.

Example

Example

#include <iostream>  

using namespace std;  //using standard namespace

template<class T>  

class A   

{  

    public:  

    T num1 = 5;  

    T num2 = 6;  

    void add()  

    {  

        cout << "Addition of num1 and num2 : " << num1+num2<<endl;  

    }  

      

};  

  

int main()   //main function

{  

    A<int> d;  

    d.add();  

    return 0;  

}

Output:

Output

Addition of num1 and num2 : 11

Explanation:

In this example, we create a template for class A. Inside the main method, we create the instance of class A named as, 'd'.

Class Template with Multiple Parameters

In C++, we can use multiple generic data types in a class template, and each generic data type is separated by a comma.

Syntax

It has the following syntax:

Example

template<class T1, class T2, ......>   

class class_name  

{  

   // Body of the class.  

}

C++ Class Template with Multiple Parameters Example

Let us take a simple example when a class template contains two generic data types.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

     template<class T1, class T2>  

    class A   

    {  

         T1 a;  

         T2 b;  

         public:  

        A(T1 x,T2 y)  

       {  

           a = x;  

           b = y;  

        }  

           void display()  

          {  

                 cout << "Values of a and b are : " << a<<" ,"<<b<<endl;  

           }  

      };  

  

      int main()   //main function

     {  

           A<int,float> d(5,6.5);  

           d.display();  

           return 0;  

     }

Output:

Output

Values of a and b are : 5,6.5

Explanation:

In this example, we have taken a class template with two type parameters (T1 and T2), which allows us to create the class objects with different data types. After that, class A stores and shows two values of types T1 and T2. In the main function, an object d of type A<int, float> is created with values 5 and 6.5, and the display function shows these values.

Non-type Template Arguments

In C++, the template can contain multiple arguments, and we can also use the non-type arguments. In addition to the type T argument, we can also use other types of arguments, such as strings, function names, constant expression, and built-in types.

Syntax

It has the following syntax:

Example

template<class T, int size>

class array

{

    	T arr[size];           // automatic array initialization.

};

In the above case, the non-type template argument is size and therefore, templates supplies the size of the array as an argument.

Arguments are specified when the objects of a class are created:

Example

array<int, 15> t1;                        // array of 15 integers.

array<float, 10> t2;                    // array of 10 floats. 

array<char, 4> t3;                      // array of 4 chars.

C++ Non-type Template Arguments Example

Let us take an example to illustrate the non-type template argument in C++.

Example

Example

#include <iostream>  

using namespace std;   //using standard namespace

template<class T, int size>  

class A   

{  

    public:  

    T arr[size];  

    void insert()  

    {  

        int i =1;  

        for (int j=0;j<size;j++)  

        {  

            arr[j] = i;  

            i++;  

        }  

    }  

      

    void display()  

    {  

        for(int i=0;i<size;i++)  

        {  

            std::cout << arr[i] << " ";  

        }  

    }  

};  

int main()   //Main Function

{  

    A<int,10> t1;  

    t1.insert();  

    t1.display();  

    return 0;  

}

Output:

Output

1 2 3 4 5 6 7 8 9 10

Explanation:

In this example, the class template is created which contains the nontype template argument, i.e., size. It is specified when the object of class 'A' is created.

Difference between Function Overloading and Function Templates

Several differences between function overloading and function templates in C++ are as follows:

Features Function Overloading Function Templates
Purpose Function overloading defines multiple functions with the same name but different arguments. It allows us to write generic functions that operate with any data type.
Flexibility It has limited flexibility to explicitly defined overloads. It is more flexible for generic programming.
Syntax It defines multiple functions with the same name but different arguments. It uses template<class T> and some other similar template declarations.
Code Duplication It needs to manually write each function version. It helps to reduce code duplication.
Maintenance It is harder to maintain. It is easy to maintain.

C++ Template MCQs

1) Which of the following options is used for generic programming?

  • Modules
  • Templates
  • Abstract Classes
  • Virtual Functions

2) Which of the following options shows the correct syntax of function templates?

  • template<typename T> returnType functionName(T arg)
  • template<class T> returnType functionName(T arg)
  • template<T> returnType functionName(T arg)
  • Both A and B

3) Which of the following options is correct about class templates in C++?

  • They cannot have member functions
  • They must be instantiated with specific types before use
  • They can only accept one type parameter
  • They are slower than regular classes

4) What will be the output of the following code?

Example

#include<iostream>

#include<stdlib.h>

using namespace std; 

template<class X, class Y>

class cpptutorial 

{

    X a;

    Y b;

};

 

int main()  

{

   cpptutorial<char, char> c;

   cpptutorial<int, int> d;

   cout << sizeof(c) << endl;

   cout << sizeof(d) << endl;

   return 0;

}

5) Can we utilize the multiple-type parameters in a template

  • Only for function templates
  • Only for class templates

Input Required

This code uses input(). Please provide values below: