Templates in C++
The keyword template is used to define the function template and class template.
It is a way to make your function or class generalize as far as the data type is a concern.
The keyword template is used to define the function template and class template.
It is a way to make your function or class generalize as far as the data type is a concern.
The template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by the keyword ‘class’.
Function template is also known as the generic template.
template<class type> type func_name(type arg1, ...);
Normal Example:
__________________________________
#include<iostream.h>
#include<conio.h>
int big (int a, int b)
{
if(a>b)
return(a);
else
return(b);
}
int main()
{
cout<<big(4,5);
cout<<big(4.5, 6.5);
getch();
}
_____________________________________
Using Template:
#include<iostream.h>
#include<conio.h>
template <class X>
X big( X a, X b)
{
if(a>b)
return(a);
else
return(b);
}
int main()
{
cout<<big(4,5);
cout<<big(4.5, 6.5);
getch();
}
or more than one template
or more than one template
#include<iostream.h>
#include<conio.h>
template <class X, Class Y>
X big( X a, Y b)
{
if(a>b)
return(a);
else
return(b);
}
int main()
{
cout<<big(4,5);
cout<<big(4.5, 6.5);
getch();
}
___________________________________
Comments
Post a Comment