Академический Документы
Профессиональный Документы
Культура Документы
C++ template is used in situation where we need to write the same function for different data
types. For example, if we need a function to add two variables. The variable can be integer, float
or double. For this purpose we have to write one function for each data type. To avoid writing the
same function for different data types we use template.
Function template
Class template
Function Template
C++ Function templates are those functions which can handle different data types without
separate code for each of them.
#include<iostream.h>
#include<conio.h>
rs = n1 + n2;
return rs;
}
void main()
{
int A=10,B=20,C;
long I=11,J=22,K;
Output :
To make a function templates, we must write the following statement before function definition.
Here T is the type name, which is dynamically determined by the compiler according to the
parameter passed to function definition.
Class Template
Like function templates, we can also use templates with class to make member function common
for different data types.
#include<iostream.h>
#include<conio.h>
T Add(T, T);
};
rs = n1 + n2;
return rs;
}
void main()
{
Addition <int>obj1;
Addition <long>obj2;
int A=10,B=20,C;
long I=11,J=22,K;
Output :