Saturday, February 2, 2013

Template & Template Function in C++


Template:
Templates are mechanism that is possible to use one function or class to handle many different data type by using template.
Template is a feature of C++ programming language that allows function and class to operate generic function.
Advantages:
                                i.            Template is linked at compile time.
                              ii.            Template reduces the size of code.
                            iii.            Templates are considered type-safe.

Disadvantages:
                                i.            The compiler generates additional code for each template type.


Syntax:
template  <class template_var> 



Template Function:



 


We can design a single function that operates on data of many types.

Syntax:
template  <class T>
return_type fun_name(argument type T)
{
            //Body of function with type T
}



Ex:

template<class T1>
void swap(T1 &x, T1 &y)
{
 T1 temp;
 temp =x;
 x=y;
 y=temp;
}
void main()
{
 int a=10,b=20;
 char x=’a’, y=’z’;
 float m=10.5, n=20.5;
 cout<<”After Swap : ”;
 cout<<”\n int a = ”<<a<<” int b = ”<<b;
 cout<<”\n char x = ”<<x<<” char y = ”<<y;
 cout<<”\n float m = ”<<m<<” float n = ”<<n;
 swap(a,b);
 swap(x,y);
 swap(m,n);
 cout<<”Before Swap : ”;
 cout<<”\n int a = ”<<a<<” int b = ”<<b;
 cout<<”\n char x = ”<<x<<” char y = ”<<y;
 cout<<”\n float m = ”<<m<<” float n = ”<<n;
 getch();
}



Template Function Overloading:
A template function may be overloaded either by template function or ordinary function.
template <class t1>
void display(t1 x)
{
 cout<<”Template function”<<x;
}
void display(int x)
{
 Cout<<”Explicit function”<<x;
}
void main()
{
 display(10);
 display(‘z’);
 display(10.50);
}

0 comments:

Post a Comment

Powered by Blogger.