Object Oriented Programming - Old Questions

6. What is template? How can you differentiate a function template from a class template? Explain.

5 marks | Asked in 2075( Old Course)

Templates is defined as a blueprint or formula for creating a generic class or a function. To simply put, we can create a single function or single class to work with different data types using templates. 

Function Template

It is used to define a function to handle arguments of different types in different times. Using function template, we can use same function for arguments of one data type in some cases and arguments of other types in other cases.

Syntax:

template<class type>
ret_type func_name(parameter list)
{
//body of the function
}

Example:

#include<iostream.h>
using namespace std;
template<class X>
X func( X a, X b)
{
 return a;
}
int main()
count<<func(15,8);      //func(int,int);
count,,func('p','q');   //func(char,char);
count<<func(7.5,9.2);   //func(double,double)
return();
}

Class Template

Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. 

Syntax:

template<class Ttype>
class class_name
{
//class body;
}

Example:

#include <iostream>
using namespace std;

template <class T>
class Calculator
{
private:
	T num1, num2;
	
public:
	Calculator(T n1, T n2)
	{
		num1 = n1;
		num2 = n2;
	}
	void displayResult()
	{
		cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
		cout << "Addition is: " << add() << endl;
		cout << "Subtraction is: " << subtract() << endl;
		cout << "Product is: " << multiply() << endl;
		cout << "Division is: " << divide() << endl;
	}
	T add() { return num1 + num2; }
	T subtract() { return num1 - num2; }
	T multiply() { return num1 * num2; }
	T divide() { return num1 / num2; }
};

int main()
{
	Calculator<int> intCalc(2, 1);
	Calculator<float> floatCalc(2.4, 1.2);
	
	cout << "Int results:" << endl;
	intCalc.displayResult();
	
	cout << endl << "Float results:" << endl;
	floatCalc.displayResult();
	
	return 0;
}