Chapter 14 Templates(??) - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Chapter 14 Templates(??)

Description:

Chapter 14 Templates An Implementation of Queue Assume integer elements are considered. class Queue { public: Queue (int = 10 ... – PowerPoint PPT presentation

Number of Views:84
Avg rating:3.0/5.0
Slides: 51
Provided by: tcu3
Category:

less

Transcript and Presenter's Notes

Title: Chapter 14 Templates(??)


1
Chapter 14 Templates(??)
2
14.1 Introduction
  • ?????????
  • ?????????????????????????
  • ???????????????????????????????,?????
  • ??????????????????????!
  • ??(template)??????????????

void printArray(const int a, const int count)
for (int i0 iltcount i)
cout ltlt ai ltlt cout ltlt endl
3
14.1 Introduction
  • Function templates and class templates
  • Programmers are enable to specify an entire range
    of related functions and related classes
  • Function-template specializations and
    class-template specializations can be generated,
    respectively.
  • Generic programming

4
Software Engineering Observation 14.1
  • Most C compilers require the complete
    definition of a template to appear in the client
    source-code file that uses the template.
  • For this reason and for reusability, templates
    are often defined in header files, which are then
    included into the appropriate client source-code
    files.
  • For class templates, this means that the member
    functions are also defined in the header file.

5
14.2 Function Templates
  • Function Templates
  • Used to produce overloaded functions that perform
    identical operations on different types of data
  • First, programmer writes a single
    function-template definition.
  • Compiler generates separate object-code functions
    (function-template specializations) based on
    argument types in calls to the function template

6
14.2 Function Templates
  • Function-template definitions
  • Starting with a template header
  • Keyword template
  • List of template parameters
  • Enclosed in angle brackets (lt and gt)
  • Each template parameter is preceded by keyword
    class or keyword typename (both are
    interchangeable)
  • Used to specify types of arguments to, local
    variables in and return type of the function
    template
  • Examples
  • templatelt typename T gt
  • templatelt class ElementType gt
  • templatelt typename BorderType, typename Filltype gt

7
Common Programming Error 14.1
  • Not placing keyword class or keyword typename
    before each type template parameter of a function
    template is a syntax error.

8
fig14_01.cpp (1 of 2)
????????template ltgt??,??????????????????
Type template parameter T specified in template
header
9
fig14_01.cpp (2 of 2)
Creates a function-template specialization of
printArray where int replaces T
Creates a function-template specialization of
printArray where double replaces T
Creates a function-template specialization of
printArray where char replaces T
10
Common Programming Error 14.2
  • If a template is invoked with a user-defined
    type, and if that template uses operators (e.g.,
    , , lt) with objects of that class, those
    operators must be overloaded.
  • Forgetting to overload such operators causes
    compilation errors.

11
Indicate Any Error
include ltiostreamgt using namespace std class
Test public Test(int s0)
a s private
int a template lttypename Tgt void
printArray(const T a, const int count)
for (int i0 iltcount i) cout ltlt
ai ltlt endl void main () Test
b4 printArray(b, 4)
Error How to fix?
12
Performance Tip 14.1
  • Remember that multiple function-template
    specializations are instantiated in a program (at
    compile time), despite the fact that the template
    is written only once.
  • For the example of fig14_01.cpp, three
    specialized functions are generated and compiled
  • printArray(const int , const int)
  • printArray(const double , const int)
  • printArray(const char , const int)

13
14.4 Class Templates
  • Class templates (or parameterized types)
  • Class-template definitions start with a header
    such as
  • templatelt typename T gt
  • Additional type parameters can be specified using
    a comma-separated list. For example
  • templatelt typename T1, typename T2 gt

14
14.4 Class Templates
  • ??????(class template)???
  • ??????????????????
  • ???????????????????????,???????,????????????
  • ?????????????????,???????????,????????????
  • ??,????????????
  • ????????(Stack)?????????????

15
An Introduction to Stack
  • A kind of data structure
  • Last-In-First-Out (LIFO)

Add a new item on the top of stack.
5
Push (A) Push (B) Push (C) Push (D) Push (E) Pop
()
E
4
D
3
C
2
B
1
A
Get the item the item at the top of stack and
remove it from the stack.
0
Which one is popped by the function Pop()?
16
Examples of Stack
0
1
2
3
4
0
(4, 1)
(4, 0)
1
(3, 0)
(3, 2)
(3, 1)
2
(2, 1)
(2, 0)
3
(1, 0)
(1, 1)
4
(0, 1)
(0, 0)
17
An Implementation of Stack
  • Implement Stack using an array.
  • Assume integer elements are considered.

class Stack public Stack (int
10) //Default constructor
Stack() bool push (int)
//Push an integer into the stack return true
if successful bool pop (int ) //Pop
an integer from the stack return true if
successful bool isEmpty() const
//Return true if the array is empty bool
isFull() const //Return true if the array
is full private int size
//array size int top
//initialized to -1 always maintain the next
index to pop int stackPtr
18
Stack (int s) size( (s gt 0)? s 10 ),
top(-1) stackPtr new intsize
Stack() delete stackPtr
bool Stackpush (int pushValue) if
(!isFull()) stackPtrtop
pushValue return true
return false bool Stack pop (int
popValue) if (!isEmpty())
popValue stackPtrtop--
return true return false
bool StackisFull () const return (top
size) bool StackisEmpty () const
return (top -1)
19
An Implementation of Stack
  • Now consider object elements.

class Point public Point(int a0,
int b0) x(a), y(b)
private int x, y
class Stack public Stack (int
10) //Default constructor
Stack() bool push (const
Point ) //Push a Point object into the
stack return true if successful bool pop
(Point ) //Pop a Point object from the stack
return true if successful bool isEmpty()
const //Return true if the array is empty
bool isFull() const //Return true if
the array is full private int size
//array size int top
//initialized to -1 always maintain the next
index to pop Point stackPtr
20
Stack (int s) size( (s gt 0)? s 10 ),
top(-1) stackPtr new Pointsize
Stack() delete stackPtr
bool Stackpush (int pushValue) if
(!isFull()) stackPtrtop
pushValue return true
return false bool pop (int
popValue) if (!isEmpty())
popValue stackPtrtop--
return true return false
bool StackisFull () return (top
size) bool StackisEmpty ()
return (top -1)
???,?????????????,?????????????????,????????????(?
???Point)????????
????????? ?????,?????????????????(????Point)??????
????????????
21
Observations
  • Stack?????????????,????????????
  • Stack????Point?????????Stack????????????????
  • Stack???????????????????(??)??????
  • ?????,?????????Stack???!
  • ????????(template)

22
Stack.h (1 of 3)
????????????,???????class template(????),?????clas
s?typename???????T,?????????????????????
????????????,????????T??????????
23
Stack.h (2 of 3)
????stackPtr?????,????T???
??????????????????,???????????????????
??!!??,Stack???????????,???????????StackltTgt,??
24
Stack.h (3 of 3)
25
Note ? ? ? ? ?
  • Software Engineering Observation 14.1
  • Most C compilers require the complete
    definition of a template to appear in the client
    source-code file that uses the template.
  • For class templates, this means that the member
    functions are also defined in the header file.
  • ???!????????,????????????,???????????,????????????
    ???????????????????(?????????),??????C??????????
    ??????????????,?????????????(?????????)????.h??,??
    ?????????,????????????????

26
fig14_03.cpp (1 of 3)
?????????????????
?????????(class-template specialization),Stackltdou
blegt? ???????double?????T??
27
fig14_03.cpp (2 of 3)
?????????(class-template specialization),Stackltint
gt? ???????int?????T??
28
fig14_03.cpp (3 of 3)
?????,?????????????,??????Stack???????double?int?
????,?????,????????Stack??????????????,???????????
???????????,???????????
29
fig14_04.cpp (1 of 3)
????,??????????????,??StackltTgt????????
????????T,????StackltTgt????????
????????????T?????????,???????????????,??????
??_______________________
30
fig14_04.cpp (2 of 3)
31
14.5 Nontype Parameters and Default Types for
Class Templates
  • Nontype template parameters
  • Can have default arguments
  • Are treated as const
  • Example
  • Template header templatelt typename T, int
    elements gt
  • In the constructor, we can use nontype
    paramemter stackPtr new T elements
  • Declaration Stacklt double, 100 gt salesFigures

32
14.5 Nontype Parameters and Default Types for
Class Templates
  • Type parameters can have default arguments too
  • Example
  • Template header templatelt typename T string
    gtDeclaration Stackltgt jobDescriptions

33
Exercise
  • Use the concept of template to implement Queue.
  • What is a queue?
  • First-In-First-Out (FIFO)

E
Add a new item on the rear of queue.
D
Push (A) Push (B) Push (C) Push (D) Pop (E) Pop ()
C
B
A
Get the item at the front of queue and remove it
from the queue.
Which one is deleted by the function Pop()?
34
An Implementation of Queue
  • Assume integer elements are considered.

class Queue public Queue (int
10) //Default constructor
Queue() bool push (int)
//Push an integer into the queue return true
if successful bool pop (int ) //Pop
an integer from the queue return true if
successful bool isEmpty() const
//Return true if the array is empty bool
isFull() const //Return true if the array
is full private int size
//array size int front, rear
//initialized to 0 int queuePtr
35
Implementing Queue Using Array
  • Suppose the length of array is n.
  • This approach runs into a problem when rear
    equals to n-1.
  • Shifting all elements to the left?
    Time-consuming.

36
Circular Queue
Push (A) Push (B) Push (C) Push (D) Pop () Pop
() Pop () Push (E) Push (F) Push (G) Push
(H) Push (I)
B
C
D
A
I
E
H
F
G
A
B
C
D
E
F
G
H
I
37

B
C
A
D
E
H
F
G
How do know whether the queue is empty or full?
38
An Implementation of Queue
Queue (int s) size( (s gt 0)? s 10 ),
front(0), rear(0) queuePtr new
intsize Queue() delete
queuePtr bool Queuepush (int
pushValue) if (!isFull())
rear (rear1) size
queuePtrrear pushValue return
true return false bool
Queue pop (int popValue) if
(!isEmpty()) front (front1)
size popValue
queuePtrfront return true
return false bool Queue isFull
() const return ((rear1) size
front) bool Queue isEmpty () const
return (rear front)
  • Assume integer elements are considered.

class Queue public Queue (int
10) //Default constructor
Queue() bool push (int)
//Push an integer into the queue return true
if successful bool pop (int ) //Pop
an integer from the queue return true if
successful bool isEmpty() const
//Return true if the array is empty bool
isFull() const //Return true if the array
is full private int size
//array size int front, rear
//initialized to -1 always maintain the next
index to pop int queuePtr
39
Implementing Queue Using Template
ifndef QUEUE_H define QUEUE_H template
lttypename Tgt class Queue public
Queue(int 10) Queue() bool
push( const T ) bool pop( T )
bool isFull() const bool isEmpty()
const private int size int
front, rear T queuePtr
1.
2.
3.
4.
40
Implementing Queue Using Template
template lttypename Tgt QueueltTgt Queue (int
s) size( (s gt 0)? s 10 ), front(0),
rear(0) queuePtr new Tsize
template lttypename Tgt QueueltTgt Queue()
delete queuePtr template
lttypename Tgt bool Queue push ( const T
pushValue ) if (!isFull())
rear (rear1) size
queuePtrrear pushValue return
true return false
5.
6.
  • Assume integer elements are considered.

7.
class Queue public Queue (int
10) //Default constructor
Queue() bool push (int)
//Push an integer into the queue return true
if successful bool pop (int ) //Pop
an integer from the queue return true if
successful bool isEmpty() const
//Return true if the array is empty bool
isFull() const //Return true if the array
is full private int size
//array size int front, rear
//initialized to -1 always maintain the next
index to pop int queuePtr
8.
9.
10.
11.
12.
41
Implementing Queue Using Template
template lttypename Tgt bool QueueltTgt pop (
T popValue ) if (!isEmpty())
front (front1) size
popValue queuePtrfront
return true return false
template lttypename Tgt bool QueueltTgt isFull ()
const return ((rear1) size
front) template lttypename Tgt bool
QueueltTgt isEmpty () const return
(rear front) endif
13.
14.
15.
class Queue public Queue (int
10) //Default constructor
Queue() bool push (int)
//Push an integer into the queue return true
if successful bool pop (int ) //Pop
an integer from the queue return true if
successful bool isEmpty() const
//Return true if the array is empty bool
isFull() const //Return true if the array
is full private int size
//array size int front, rear
//initialized to -1 always maintain the next
index to pop int queuePtr
16.
17.
18.
19.
42
7.11 Introduction to C Standard Library Class
Template vector
  • C-style pointer-based arrays
  • Have great potential for errors and several
    shortcomings
  • C does not check whether subscripts fall
    outside the range of the array
  • Two arrays cannot be meaningfully compared with
    equality or relational operators
  • One array cannot be assigned to another using the
    assignment operators

43
7.11 Introduction to C Standard Library Class
Template vector
  • Class template vector
  • Available to anyone building applications with
    C
  • Can be defined to store any data type
  • Specified between angle brackets in vectorlt type
    gt
  • All elements in a vector are set to 0 by default
  • Member function size obtains size of array
  • Number of elements as a value of type size_t
  • vector objects can be compared using equality and
    relational operators.
  • Assignment operator can be used for assigning
    vectors.
  • Individual elements can be accessed with square
    brackets.

44
7.11 Introduction to C Standard Library Class
Template vector
  • vector member function at
  • Provides access to individual elements
  • Performs bounds checking
  • Throws an exception when specified index is
    invalid
  • Accessing with square brackets does not perform
    bounds checking

45
fig07_26.cpp (1 of 6)
??!??vector?????????ltvectorgt???
vectorltintgt????????,????????????
????vector???int??
vector??????????size,???????????
46
fig07_26.cpp (2 of 6)
???????vector????????????_______??!????
???????vector????????,??????????????????_______??_
________
47
fig07_26.cpp (3 of 6)
vector???????,?????????????????????????????????
??at()?????????????????????????????
48
fig07_26.cpp (4 of 6)
49
Execution Result
fig07_26.cpp (5 of 6)
50
Execution Result
fig07_26.cpp (6 of 6)
??????,at()????????
Write a Comment
User Comments (0)
About PowerShow.com