Template in C++

Advertisements

C++ Template

C++ template is used in situation where we need to write the same function for different data types. For example, if we need a function to add two variables. The variable can be integer, float or double. For this purpose we have to write one function for each data type. To avoid writing the same function for different data types we use template.

There are two types of templates in C++ :

  • Function template
  • Class template

Function Template

C++ Function templates are those functions which can handle different data types without separate code for each of them.


       #include<iostream.h>
       #include<conio.h>

       template <class T>
       T Sum(T n1, T n2)                      // Template function
       {
              T rs;

              rs = n1 + n2;

              return rs;

       }

       void main()
       {
              int A=10,B=20,C;
              long I=11,J=22,K;

              C = Sum(A,B);                     // Calling template function
              cout<<"\nThe sum of integer values : "<<C;

              K = Sum(I,J);                        // Calling template function
              cout<<"\nThe sum of long values : "<<K;

       }

   Output :

              The sum of integer values : 30
              The sum of long values : 33

				

To make a function templates, we must write the following statement before function definition.


       template <class T>
       

Here T is the type name, which is dynamically determined by the compiler according to the parameter passed to function definition.

Class Template

Like function templates, we can also use templates with class to make member function common for different data types.


	#include<iostream.h>
	#include<conio.h>

	template <class T>
	class Addition                                    // Template class
	{
		  public:

		  T Add(T, T);
	};

	template <class T>
	T Addition<T>::Add(T n1, T n2)           // Template member function
	{
		  T rs;

		  rs = n1 + n2;

		  return rs;
	}

	void main()
	{

		  Addition <int>obj1;
		  Addition <long>obj2;


		  int A=10,B=20,C;
		  long I=11,J=22,K;

		  C = obj1.Add(A,B);                    // Calling template member function
		  cout<<"\nThe sum of integer values : "<<C;

		  K = obj2.Add(I,J);                        // Calling template member function
		  cout<<"\nThe sum of long values : "<<K;

	}

	Output :

			  The sum of integer values : 30
			  The sum of long values : 33

Advertisement