A class or function which can operate any type of with single bunch of code (Run time data type initialization)
Template is one of the features
added to C++ recently. It is a new concept which enable programmer to make generic
class which can operate any data type. A Template class takes data type as an
argument which run time set data type of calling object so there is no need to
make different version of class and function different types of data type.
Syntax:
Template
<Class name Ob_Name>
Class
Class_name
{
_____
_____
}
A template can be considered as a
kind of macros. When an object of a specific type is defined for actual use. The
template definition for that class is substituted with the required data type. since
a template is defined with a parameter that would be replaced by a specific
data type at the time of actual use of the class or function. The template is sometimes called
parameterized or function.
/* ##############################
Girfa Student Help
Template Class
Date : 21-Sep-2016
for more example visit: http://girfahelp.blogspot.in/p/c-tutorial_20.html
###############################
*/
#include<iostream.h>
#include<conio.h>
const int size=3;
template <class t>
class vector
{
t *v;
public:
vector()
{
for(int i=0;i<size;i++)
v[i]=0;
}
vector(t *a)
{
for(int i=0;i<size;i++)
v[i]=a[i];
}
t operator +(vector &y)
{
t sum=0;
for(int i=0;i<size;i++)
sum+=v[i]+y.v[i];
return sum;
}
}
void main()
{
int x[3]={1,2,3};
int y[]={4,5,6};
vector <int> v1;
vector <int> v2;
v1=x;
v2=y;
int r=v1+v2;
cout<<"\n\tSum of int\t="<<r;
float x1[3]={1.1,2.2,3.3};
float y1[]={4.1,5.5,6.6};
vector <float> v3;
vector <float> v4;
v3=x1;
v4=y1;
r=v3+v4;
cout<<"\n\tSum of float\t="<<r;
}
Template Function
Template function reduce coding so there is no need to make specific version to specific data type . One function can hadnle any data type including user defined data class and structure etc.
/* #################################
Girfa : Student Help
Template Function
for more C++ Program Visit : http://girfahelp.blogspot.in/p/c-tutorial_20.html
#################################
*/
#include<iostream.h>
template <class G>
void printallformat(G s)
{
cout <<endl<<s;
}
int main()
{
printallformat(1); // Printing Integer
printallformat('a'); //Printing character
printallformat(7.5); // Printing float
printallformat("Girfa:Student Help"); // Printing String
No comments:
Post a Comment