Image

C++ - Templates - Templates

Templates

Templates in programming allows functions or class to work on one or more datatype at once without writing different codes for different datatype. Templates are often used in larger program for the purpose of code reusability and flexibility of any programs. The concept of template can be used in two different ways.

1. Function Template
2. Class Template
Function Template
Syntax:
	Template <class T>
	T.some_function(T args)
	{
	….
	….
	}
e.g: WAP to display larger number among two number using function template.
#include<iostream.h>
#include<conio.h>
template<class T>
T large(T n1,T n2)
{
  return (n1>n2)?n1:n2;
}

void main()
{
 clrscr();
 int i1,i2;
 float f1,f2;
 char c1,c2;
 cout<<"Enter two integer ";
 cin>>i1>>i2;
 cout<<"Enter two float ";
 cin>>f1>>f2;
 cout<<"Enter two character ";
 cin>>c1>>c2;
 cout<<"\nLarger integer "<<large(i1,i2);
 cout<<"\nLarger float "<<large(f1,f2);
 cout<<"\nLarger character "<<large(c1,c2);
 getch();
}
O/P
Enter two integer
2   
3
Enter two float
2.3
4.5
Enter two character
A
G
Large integer  3
Large float   4.5
Large character  G
WAP to swap elements using function templates
#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &n1,T &n2)
{
 T temp;
 temp=n1;
 n1=n2;
 n2=temp;
}
void main(){
 clrscr();
 int i1=1,i2=2;
 float f1=1.1,f2=2.2;
 char c1='a',c2='b';
 cout<<"\n Before Passing Data ";
 cout<<"\ni1 = "<<i1<<"\t\ti2 = "<<i2;
 cout<<"\nf1 = "<<f1<<"\tf2 = "<<f2;
 cout<<"\nc1 = "<<c1<<"\t\tc2 = "<<c2;
 swap(i1,i2);
 swap(f1,f2);
 swap(c1,c2);
 cout<<"\n After Passing Data ";
 cout<<"\ni1 = "<<i1<<"\t\ti2 = "<<i2;
 cout<<"\nf1 = "<<f1<<"\tf2 = "<<f2;
 cout<<"\nc1 = "<<c1<<"\t\tc2 = "<<c2;
 getch();
}
O/P
Before Passing Data
I1=1        I2=2
F1=1.1    F2=2.2
C=a         C=b
After Passing Data
I1=2       I2=1
F1=2.2   F2=1.1
C1=b      C2=a