• A template is keyword in C++ that is used to make your function or class generalize as far as the data type is a concern.
  • Template keyword used before function and class.
  • Function Template Syntax
template <class type >  type function_name(type arg1,...) 
  • Class Template Syntax
template<class type> class class_name { ..... };

Why we use the Template keyword?

Let us take example to explain this

Function Template

#include <iostream>

using namespace std;

int SmallNumber(int a,int b)
{
    if(a<b)
    {
        cout<<a<<endl;
    }
    else
    {
        cout<<b<<endl;
    }
    
    return 0;
}

int main()
{
   SmallNumber(4,5); 
   // We given float number as parameter
   SmallNumber(4.4,5.5);

    return 0;
}
Output: 4
        4

Here we see that the output of different parameter gives the same output. So for Float parameter pass to the function, we have create different functions there the parameter is float. So problem is in this we have to create a different function for the different-different data type.It is very complex and time taking . To solve this problem we use template keyword.  To Solve the example we use template

#include <iostream>

using namespace std;

template <class x> x SmallNumber(x a,x b)
{
    if(a<b)
    {
        cout<<a<<endl;
    }
    else
    {
        cout<<b<<endl;
    }
    
    return 0;
}

int main()
{
   SmallNumber(4,5); 
   // We given float number as parameter
   SmallNumber(4.4,5.5);

    return 0;
}
Output: 4
        4.4

Here output different, for different datatype.

We also use different template for different paramater.

template <class x,class y> x function_name(x a, y b)

 

Class Template

Same as function template, Class template are useful when class is defined to something that is independent of the datatype.                                                                                                   Following example for Class Template.

#include <iostream>
using namespace std;

template <class x>
class opertaion
{
private:
    // a and b type of x
	x a, b;
	
public:
	opertaion(x n1, x n2)
	{
		a = n1;
		b = n2;
	}
	

	x add() { 
	    x sum= a + b;
	    cout<< sum <<endl;
	    
	}
	
	x subtract() { 
	    x sub =a - b;
	    cout<<sub<<endl;
	    }
	
};

int main()
{
	opertaion<int> intOperation(2, 1);
	opertaion<float> floatOpertaion(2.4, 1.2);
	
	// For int type 
	intOperation.add();
	intOperation.subtract();
	
	// For float type
	floatOpertaion.add();
	floatOpertaion.subtract();
	
	return 0;
}
Output: 3
        1
        3.6
        1.2

For more about the template.

Leave a Reply

%d bloggers like this: