object oriented programming - templates
TRANSCRIPT
-
8/7/2019 Object Oriented Programming - Templates
1/22
Object OrientedProgramming
Templates
-
8/7/2019 Object Oriented Programming - Templates
2/22
Problemsofoverloading
Consider following function
Ifwe want tocompare many types with max() Write a separate overloaded versions for each
type
We might use polymorphism We might use macros
int max (int x, int y) {
return (x > y) ? x : y;
}
#define max (x,y) (( x > y) ? x : y)
Class overloading?
-
8/7/2019 Object Oriented Programming - Templates
3/22
Introduction
Getting Reuse Through Templates Inheritance sometimes isnt enough nor is itappropriate
What are Templates?
An attempt towrite Genericcode Parameterized Types Until certain point they fulfill the functionalityof
macro Compact way to make overloaded functions(classes?)
-
8/7/2019 Object Oriented Programming - Templates
4/22
Introduction
Types of templates Function templates Allows towrite generic functions
Class Templates
Allows towrite genericclasses Basic steps
Define a templates
Instantiate
-
8/7/2019 Object Oriented Programming - Templates
5/22
template < class identifier >
ReturnType FunctionName (arguments of type identifier)
Defininga Function Template
template < class T >T max (T x, T y) {
return (x > y) ? x : y;
}
Keyword for declaring function templateKeyword class
Name of the template data-type
Function parameters of type
template, primitive or user-defined
-
8/7/2019 Object Oriented Programming - Templates
6/22
Function TemplateInstantiation
Once a template function is defined, it can beused like other functions
max(7, 8); //max(int, int)
max(2.3, 4.5); //max(double, double)
Myclass a, b;
max (a, b); //max(Myclass, Myclass)
Yourclass c, d;
max (c, d); //max(Yourclass, Yourclass)
Onlyone version is generated for each data
type
-
8/7/2019 Object Oriented Programming - Templates
7/22
Template Arguments
If a template argument cannot be deduced from function
parameter, it must be specified explicitly
int s1 = typeLength(); //T is int
int s2 = typeLength(); //T is double
int s3 = typeLength(); //T is clar
template < class T >
int typeLength () {
return 8*sizeof(T);
}
Another example
void g(int i) {implicit_cast(i); //error: cann;t deduce T
implicit_cast(i); //T is double, U is int
implicit_cast(i);//T is char, U is double
implicit_cast(i); //T is char*, U is int; error: cannot
//convert from int tochar*
}
template < class T, class U >
T implicit_cast(U u) {
return u;
}
-
8/7/2019 Object Oriented Programming - Templates
8/22
Function Template Overloading
template template
T max (T x, T y)T max (T x, T y)
{{
return (x > y) ? x : y;return (x > y) ? x : y;
}}
void fn (int i, char c)void fn (int i, char c)
{{
max (i , i);max (i , i); // ok// ok
max (c, c);max (c, c); // ok// ok
max (i, c);max (i, c); // illegal// illegal}}
template template
T max (T x, T y)T max (T x, T y)
{{
return (x > y) ? x : y;return (x > y) ? x : y;}}
int max (int , char);int max (int , char);
// explicit// explicit
void fn (int i, char c)void fn (int i, char c)
{{
max (i , i);max (i , i); // ok// okmax (c, c);max (c, c); // ok// ok
max (i, c);max (i, c); // ok// ok
}}
-
8/7/2019 Object Oriented Programming - Templates
9/22
Function Template Overloading
Function templatesFunction templates can be overloaded.can be overloaded.char *max (char *st1, char *st2) {char *max (char *st1, char *st2) {
return strcmp(st1, st2) > 0 ? x: y;return strcmp(st1, st2) > 0 ? x: y;
}}
Declared explicitly here, this functionwill beDeclared explicitly here, this functionwill becalled if the arguments are of type char*.called if the arguments are of type char*.
-
8/7/2019 Object Oriented Programming - Templates
10/22
Function Template Overloading
Non-template functions with same name Different function arguments
Other function templates with same name
Different parameters
template template
T max( T a[], int size) {T max( T a[], int size) {
int index = 0;int index = 0;
for(int i=1; i a[index] ) index = i;
return a[index];return a[index];
}}
-
8/7/2019 Object Oriented Programming - Templates
11/22
Usingmax with Rational class
templatetemplate
T max( T a[], int size);T max( T a[], int size);
main(){main(){
Rational v[20];Rational v[20];
Rational mr = max(v, 20); // Problem ?Rational mr = max(v, 20); // Problem ?
}}
bool Rational :: operator>(const Rational& r) {bool Rational :: operator>(const Rational& r) {
if (num*r.den > r.num*den)if (num*r.den > r.num*den)
return true;return true;
elseelsereturn false;return false;
}}
-
8/7/2019 Object Oriented Programming - Templates
12/22
Overloadresolution
Compiler performs matching process
Tries to find precise match of functionname and argumenttypes
If fails, function template generates function-templatespecialization and uses most specialized one
//sqrt(complex) is more specialized than
sqrt(complex)
This is because, anycall that matches sqrt(complex)
also matches sqrt(T)
template T sqrt(T);template
complex sqrt(complex);
double sqrt(double);
complex z;sqrt(1); //sqrt(int)
sqrt(2.0); //sqrt(double)
sqrt(z); //sqrt(complex)
-
8/7/2019 Object Oriented Programming - Templates
13/22
Template Function Specialization
By default a template gives a single definition to be used for everytemplate argumentdoes not make sense always
template
bool less(T a, T b) {
return a
-
8/7/2019 Object Oriented Programming - Templates
14/22
Template Function Specialization
Another exampleclass Stack {
int size, top, *a;
Stack operator=(const Stack&);
/**/
}
Stack s1(1000), s2(2000);
swap(s1, s2); //inefficient
template
void swap(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
void Stack:::swap(Stack &s) {
swap(size, s.size);
swap(top, s.top);swap(a, s.a);
}
//swap for Stack
template
void swap(Stack &a, Stack &b) {
a.swap(b);
}
-
8/7/2019 Object Oriented Programming - Templates
15/22
Template Classes
Manyclasses are relatively insensitive to thedata type of their members
Containerclasses carryout similaroperations to add remove find
The operations are the same whatever the typeof the data members
-
8/7/2019 Object Oriented Programming - Templates
16/22
Example: A Generic Stack
bottom
top
...
...
...
...
Operations:
poppush
empty
fullinitialize
destroy
-
8/7/2019 Object Oriented Programming - Templates
17/22
A Stack ofIntegers
class Stack {
int* top, bottom;int size;
public:
Stack(int);
bool push(int);bool pop(int&);
bool empty();
bool full();
~Stack();
};
-
8/7/2019 Object Oriented Programming - Templates
18/22
A Class Template
template class Stack {
T *top, *bottom;int size;
public:
Stack(int);
bool push(const T&);bool pop(T&);
bool empty();
bool full();
~Stack():
};
-
8/7/2019 Object Oriented Programming - Templates
19/22
Classimplementations
template
Stack :: Stack(int sz)
{
size = sz;
top = bottom = new T [sz];
}
template
bool Stack :: push(const T& x)
{
if (full()) return false;
*top++ = x;
return true;
}template
bool Stack :: empty()
{if (top == bottom)
return true;
return false;
}
template
bool Stack :: pop(T& x){
if (empty()) return false;
x = *--top;
retrun true;
}
-
8/7/2019 Object Oriented Programming - Templates
20/22
Cont.
template
Stack :: ~Stack()
{
delete [] bottom;
}
template
bool Stack :: full()
{
if (top-bottom >= size)
return true;
return false;
}
-
8/7/2019 Object Oriented Programming - Templates
21/22
Using Stack Template
main()
{
Stack si(100);
Stack sc(20);Stack sf(25);
Stack sr(50);
Stack se(90);
...
...
int i = 0;
while (!si.full())si.push(i++);
int a;
while(!si.empty()) {
s1.pop(a);
cout
-
8/7/2019 Object Oriented Programming - Templates
22/22
Templateparameters
templateclass Buffer {
//
}
Buffer cbuf;
Buffer rbuf;
A template can take
Type parameter Ordinary type Template parameter
Cannot take non-const expression
void f(int i) {
Buffer bx; //error: const expressionexpected
}