Templates Powerpoint CPP
Templates Powerpoint CPP
TEMPLATES IN C++
PRESENTED TO :-
MR VIJAY KUMAR BY:- ADITYA SEHRAWAT
ASST PROFF BCA DEPT. SAHIL AHLAWAT
WHAT IS A TEMPLATES.
$ It is a concept which enables us to define
generic (shared) classes and functions and
thus provides support for generic
programming,
$ A template can be used to create a family of
classes or functions.
For example, a class template for an array
class would enable us to create arrays of
various data types such as int array and float
array.
$ Templates are sometimes called
parameterized classes or functions.
TYPES OF TEMPLATES
$ Function templates.
$ class templates.
A SIMPLE PROGRAM WITHOUT TEMPLATE
#include<iostream.h>
#include<conio.h>
Using namespace std;
Int max(int a,int b)
{ if (a>b)
Return (a);
else
return(b); }
Float max(float a, float b)
{ if(a>b)
Return(a);
else return(b); }
Int main()
[ cout<<max(20,40)<<endl;
cout<<max(10.6,50.8)<<endl;
}
FUNCTION TEMPLATE
$ A function template defines a family of functions.
$ SYNTAX :
template<class T>
return type function_name (argument of type T)
{
//……..
// body of function
// ……..
}
FUNCTION TEMPLATE WITH MULTIPLE PARAMETER
#include<iostream.h>
#include<conio.h>
Template<class T1 , class T2>
Void display(T1 x ,T2 y)
{
cout<<x<<“ “<<y<<“\n”;
}
int main()
{
display(1999,”EBG”);
display(12.34 , 1234);
return 0;
}
CLASS TEMPLATE
$ The class template definition is very similar to an ordinary class
definition except the prefix template<class T> and the use of
type T.
This prefix tells the compiler that we are going to declare a template
and use T as a type name in the declaration.
$ Syntax:
template<class T>
class classname
{
//……
//class member specification
//……
} };
CLASS TEMPLATE WITH MULTIPLE PARAMETERS
#include<iostream.h>
Template<class T1 , class T2>
Class test
{ T1 a;
T2 b;
public : test(T1 x,T2)
{ a=x , b=y; }
void show()
{ cout<<a<<“ and” << b <<“\n” ; } };
Int main()
{ test<float,int>test 1(1.23 ,123);
test<int ,char> test 2(100,’w’);
test 1.show();
test2.show();
return 0;