Describe how to construct function templates and class templates.
Describe how to construct function templates and class templates.
Templates:
Templates are used for writing generic programs. These work like macros.
The compiler checks the type before template expansion. The source code have class or function although the compiled code may have several copies of same class or function.
Data type is passed as a parameter so that same code is not needed to be written for different data types.
Function templates:
These templates are used for working with generic types. They help in creating a function template whose functionality may be used by more than one data type.
A template parameter is used for passing a type as argument.
It works like regular function arguments which are used for passing values to a function, template parameters allow to pass also types to a function.
The syntax is as follows:
The difference between following prototypes is the use the keywords typename or class.
template <class > declaration;
template <typename > declaration;
Class template:
Class templates are like function templates which are useful for defining classes which do not depend on the data type. The type is specified when the object of the class is declared.
The syntax is as follows:
template<class Ttype>
class class_name
{
//data members
//member functions
}
Creating object of that class:
class_name<type> obj;
Example of function template:
#include <iostream>
using namespace std;
//function template
//function that adds two values
template<class Temp> Temp add(Temp &a,Temp &b)
{
Temp sum = a+b;
return sum;
}
int main()
{
//int variables
int i =3;
int j =3;
//float variables
float m = 4.3;
float n = 5.2;
//sum of int variables
cout<<"Sum of i and j is :"<<add(i,j)<<endl;
//sum of float variables
cout<<"Sum of m and n is :"<<add(m,n);
return 0;
}
Output:
Step by step
Solved in 3 steps with 2 images