In: Computer Science
In C++ please.
3. Define templates and explain their purpose. Differentiate
standalone function and class templates. Give an example of a class
template and a function template.
A template is an important feature used in C++, is used for generic programming, and defines generic functions and constructors(classes).
Generally, a template is used to create a function or
constructor(class) to work with different data types.
It means that a template function or class can work with any data
types with one definition.
There are two types of template:
1) Function template - Concerns with a function
2) class template - concerns with a constructor of a class.
The purpose of the template is to provide a definition that can
take any data type, so the main purpose is reusability and
flexibility.
In Simple words, a standalone function can't work with the
different data types with one definition and does return value, but
the class template can work with different data types with one
definition but doesn't return anything, as the class template is
nothing but a constructor of a class that works with different data
types.
Example of a class template and a function template :
class template : (Addition of two numbers )
#include<iostream>
using namespace std;
template <class T1, class T2>
class Demo
{
public :
T1 x;
T2 y;
Demo(T1 x1, T2 y1)
{
x=x1;
y=y1;
}
void addition()
{
cout<<"Addition of two numbers:
"<<(x+y)<<endl;
}
};
int main()
{
Demo<int,double> demo1(100,200.500);
demo1.addition();
Demo<int, int> demo2(10,20);
demo2.addition();
return 0;
}
function template: (addition of two numbers)
#include<iostream>
using namespace std;
template<class T1,class T2>
void addition(T1 x, T2 y)
{
cout<<"Addition of "<<x<<" and
"<<y<<" is "<<(x+y)<<endl;
}
int main()
{
addition(100,200);
addition(25.85, 36.88);
addition(1000,255.56);
return 0;
}