Object Oriented Programming Part 8 - PowerPoint PPT Presentation

1 / 16
About This Presentation
Title:

Object Oriented Programming Part 8

Description:

We have seen how to make manipulation of an polymorphic array (container) generic. ... This way allows us to make generic implementation that we can reuse in ... – PowerPoint PPT presentation

Number of Views:75
Avg rating:3.0/5.0
Slides: 17
Provided by: hann7
Category:

less

Transcript and Presenter's Notes

Title: Object Oriented Programming Part 8


1
Object Oriented ProgrammingPart 8
  • Hannu Laine

2
Generic programming
We have seen how to make manipulation of an
polymorphic array (container) generic. Different
types of objects needed their own implementation
for each object but at the higher level the
program was generic. Inheritance, pointers, virt
ual methods were used to achieve this generic
nature of the program. In C there is another wa
y to achieve genericity. This way allows us to
make generic implementation that we can reuse in
different situations. This concept is called temp
late. We can have function templates and class
templates. C standard template library (STL) is
totally based on this concept.
3
Introduction to templates
Templates are based on the feature that type can
be a kind of parameter in the function definition
or class definition. If only one or more types o
f function parameters or class data members
differentiates functions or classes, we can write
only one definition for it. This definition is
not a real function or class definition. It is
function or class template. The compiler can, us
ing the template, generate (instantiate) real
functions or real classes when they are needed.
(It is possible to use macros for this purpose in
C (as you have learned in C course).)
Templates are better than macros, because they
are easier to use and compiler does type checking
for template function parameters and for member
functions of template class. The template defini
tion is called function template or class
template. The function or class instantiated fro
m template is called template function or
template class. Templates save programmers work,
because he does not need to write many almost
similar functions or classes.
4
Template functions
Template functions can be used in cases where
several functions that have identical function
body are needed and the only difference is in
types of function parameters.
Compiler generates the code for these functions
when programmer gives a model or template of
the function. Template functions are based on fun
ction overloading. The type of a parameter is (or
types of parameters are) a kind of parameter in
function template. No explicit instantiation is n
eeded. Function call initiates the instantiation
if there is a suitable template.
It is possible to instantiate the function
explicitly in the function call (see example
later). Although programmer writes the function o
nly once (function template) internally in the
object code there are many separate functions one
for each instantiation (one for each different
parameter type combination). The idea of function
overloading is first recalled.
5
How function overloading works internally
Source code void print(const float arr, int n)
void print(const int arr, int n) int main()
int t15 1, 2, 3, 4, 5 float t25 1
.0, 2.0, 3.0, 4.0, 5.0 print(t1, 5)
print(t2, 5) return 0 void print(cons
t float arr, int n) cout or (int i 0 i rr i t n) cout i
6
How function overloading works internally
In assembly language Function calls in main
print(t1, 5) is compiled to call
_at_printqpxii print(t2, 5
) is compiled to call _at_printqpxfi
Fuction implementations void print(const int a
rr, int n) generates the code
_at_printqpxii proc near procedure instruction
s _at_printqpxii endp void print(const float ar
r, int n) generates the code _at_printqpxfi proc n
ear procedure instructions _at_printqpxfi end
p
7
Example of template function
Example. (Function Copy, that makes a copy of an
array). //Function template template Telem //or template void Copy(
Telem dest, const Telem source,int n)
int i for ( i 0 i t i source i //How to use functi
on template int main(void) float farr15
1.0, 2.0, 3.0, 4.0, 5.0, farr25
Point parr14 1.0,1.0, 2.0,2.0,
3.0,3.0, 4.0,4.0,
parr24 Copy(farr2,farr1, 5) //implicit ins
tantiation //Copy(farr2, farr1, 5) //e
xplicit inst. Copy(parr2,parr1, 4) //implicit
instantiation //Copy(parr2,parr1, 4)
//implicit inst. ... Remark. Compiler ne
eds the whole template to generate the code.
This means that it is not possible to separate
the template definition in its own file
and compile it separately. Usually template def
initions are stored in header files (new
keywords external in this context).
8
Requirements for type parameters
When new template functions are instantiated the
real types need to provide the interface that is
used in the function template.
In our example on the previous page this only
means, that it must implement to assignment
operator. Templates should be designed carefully
so that there is no special requirements that can
cause difficulties when user of the template
makes new instantiations from it.
The minimum function in the example 2 on page
11 can be implemented as a template function.
Lets do it in two different ways to demonstrate
how we can put unnecessary requirements for type
parameters and how we can avoid them.
9
Template classes
Template classes can be used when several classes
that have almost identical class definitions are
needed and the only difference is in types used
to define data members and function members.
Class template can be regarded as a class
definition where one or more types are
parameters. Compiler generates the code for real
class definitions when programmer explicitly
instantiates a class. Compiler uses a class
template as a model or as a template.
There is no implicit instantiation for classes as
was the case for template functions.
Member functions of the class template are
defined as function template. This means that
they are instantiated implicitly when they are
called first time.
10
Example 1
//class template template T2 class Pair public Pair(T1 first0, T2
second0) T1 getFirst() const T2 getSecond(
) const private T1 first T2 second
//How to use it void main(void) Pair, int name_no(Matti, 123456)
//Explicit class instantiation
cout inst. cout //Member function templates template me T1, typenameT2 PairPair(T1 first0,
T2 second0) first(first0), second(second0)
template T1
PairgetFirst() const return first
template
T2 PairgetSecond() const return
second
11
More examples
All kinds of containers are good examples of
usefulness of class templates. If we need a
container for integers, doubles, strings and
persons we have to write separate implementations
of containers for each item type unless we have
class templates. Using class template we can writ
e only one class template and ask compiler to
generate instances for all different container
types. Our first example of container classes is
IntelligentArray. We have already implemented cl
ass IntelligentArray for float numbers.
If we define this class as a class template, we
can easily instantiate intelligent arrays for all
item types we ever can meet (for each build in
type as well as for each user defined type).
See example on the next page.
12
Example 2 (Intelligent Array, part 1)
include inline int minimum(int a,int
b) return aem class IntelligentArray //Class definition
private Telem array int ca
pasity //size of allocated space
public IntelligentArray(int initial
_size, Telem init_value) int size() const
void resize(int new_size) Telem ope
rator( int i) int main(void) //Main pr
ogram IntelligentArray array(5, 0)//
initial size 5, all 0 int i cout \n The size is " for ( i 0 i if ( i array.size())
array.resize(array.size() 5)
arrayi i f
or (i 0 i 13
Example 2 (Intelligent Array, part 2)
//Implementation of intelligent array
template IntelligentArrayIntelligentArray(int initial_size, Telem
init_value) capasity initial_size
array new Teleminitial_size
for (int i 0 i arrayi init_value template me Telem int IntelligentArraysize() con
st return capasity template lem void IntelligentArrayresize(int new
_size) int min, i Telem new_array
min minimum(capasity, new_size)
new_array new Telemnew_size
for (i 0 i new_arrayi arrayi
delete array array new_array
capasity new_size template Telem IntelligentArrayoperator(int
i) return arrayi
14
Different template parameters
  • Type parameters can have default values
  • template
  • class Pair the rest is as before
  • Constant parameters
  • template
  • The SIZE must be compile time constant.
  • See a complete example later
  • Example 3 (Queue template)
  • Queue as a class template.
  • See example program on separate paper.
  • Remark. When template class is instantiated, the
    type parameter can be an instance of another
    class template.

15
Additional information
If Queue is a class template, then Queue is not a
real class name. It is not correct to instantiate
object from it like Queue queue //not correc
t Queue or Queue are real types, bec
ause compiler generates them when encountered in
the program. So following object declarations are
correct Queue intQueue Queue doubleQueue It is also possible to define new
names for these types using typedef as follows
typedef Queue QueueForInts
typedef Queue QueueForDoubles
After that it is possible to declare objects
like QueueForInts intQueue QueueForDouble
s doubleQueue Non-type parameters in class templ
ate Class template can also have a non-type para
meter. It is possible for example to pass the si
ze of the queue as a non-type parameter.
Then the class template definition starts with
expression template
16
Friends of template classes
Example 1. template class X fr
iend void f() f is a friend of every templa
te class instantiated from class template X
Example 2. template class X fri
end void f(X) void f(X) is a friend o
f class X Example 3. template c
lass X friend Y class Y is a friend of
all template classes instantiated from class
template X Example 4. template clas
s X friend Y class Y is a friend
of class X
Write a Comment
User Comments (0)
About PowerShow.com