Professional Documents
Culture Documents
TEMPLATES
TEMPLATES
TEMPLATES
else
return a;
int maximum(Poo
if (a > b)
a, Poo
return }
intb)maximum(Loo
a;
return b;
a, Loo b) 10s and 100s of data types
int maximum(Knafn
return b;{ a, Knafnelseb) {
{} if (a > b) return b; if (a > b)
if (a > b) return} a; return a;
return a; else else
else return b; return b;
return b; } }
} 2
S.Muralidharan 1
Dept of EEE Object Oriented Programming
C++ TEMPLATE
• For creating generic programming.
• Are used for the creation of set of functions and classes can be used to access all
kinds of data type.
• When an object of specific type is defined the template definition is replaced with
the required data type.
FUNCTION
TEMPLATE CLASS
TEMPLATE
Are used to create Are used to create
family of functions with family of objects with
different data types different data types of
data members.
C++
TEMPLATE
FUNCTION
TEMPLATE
S.Muralidharan 2
Dept of EEE Object Oriented Programming
A Template Function
Class means
classification not CLASS
Called “Template
Syn::
Syn Prefix”
Template<class TDT
TDT>>
returntype functionname
functionname((TDT arg1,
arg1,TDT
TDT arg2)
{
fn body;
}
#include <iostream>
int main()
{
print(10);
print(3.14f);
print('Y');
print("welcome");
return 0;
}
6
S.Muralidharan 3
Dept of EEE Object Oriented Programming
Another example
S.Muralidharan 4
Dept of EEE Object Oriented Programming
10
T2 Not Used
Missing
Template prefix
11
S.Muralidharan 5
Dept of EEE Object Oriented Programming
#include <iostream>
int main()
{
print(10,3.14);
print(3.14,55);
print('Y‘,100);
return 0;
}
12
Try by yourself..
13
S.Muralidharan 6
Dept of EEE Object Oriented Programming
CLASS TEMPLATE
15
▰ Class templates
▻ Allow type-specific versions of generic classes
Format:
template< class T >
class ClassName
{
definition
}
S.Muralidharan 7
Dept of EEE Object Oriented Programming
Example
main()
template<class t> {
class num num<int> N1(10,20,30);
{ N1.display();
t a,b,c; Num<float> N2(3.14,5.17,6.25);
public: N2.display();
num(t x,t y,t z) }
{
a=x;
b=y;
c=z;
}
void display()
{
cout<<a<<“”<<b<<“ “<<c<<endl;
}
};
17
Another example
complex operator+(complex<T> oo)
{
complex<T> res;
#include <iostream> res.rl=rl+oo.rl;
using namespace std; res.img=img+oo.img;
template<class T> return res;
class complex }
{ T rl,img; void display()
public: {
complex(){} cout<<rl<<"+i"<<img<<endl;
complex(T a,T b) }};
{ rl=a;
img=b; int main()
} {
complex add(complex<T> oo) complex<int> C1(10,20);
{ complex<int> C2(30,40);
complex<T> res; complex<int> C3;
res.rl=rl+oo.rl; // C3=C1.add(C2);
res.img=img+oo.img; C3=C1+C2;
return res; C3.display();
} return 0;
18
}
S.Muralidharan 8
Dept of EEE Object Oriented Programming
19
Constructor
Function
20
S.Muralidharan 9
Dept of EEE Object Oriented Programming
21
22
S.Muralidharan 10