Title: Chapter 14 Templates(??)
1Chapter 14 Templates(??)
214.1 Introduction
- ?????????
- ?????????????????????????
- ???????????????????????????????,?????
- ??????????????????????!
- ??(template)??????????????
void printArray(const int a, const int count)
for (int i0 iltcount i)
cout ltlt ai ltlt cout ltlt endl
314.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
4Software 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.
514.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
614.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
7Common Programming Error 14.1
- Not placing keyword class or keyword typename
before each type template parameter of a function
template is a syntax error.
8fig14_01.cpp (1 of 2)
????????template ltgt??,??????????????????
Type template parameter T specified in template
header
9fig14_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
10Common 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.
11Indicate 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?
12Performance 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)
1314.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
1414.4 Class Templates
- ??????(class template)???
- ??????????????????
- ???????????????????????,???????,????????????
- ?????????????????,???????????,????????????
- ??,????????????
- ????????(Stack)?????????????
15An 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()?
16Examples 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)
17An 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)
19An 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)??????
????????????
21Observations
- Stack?????????????,????????????
- Stack????Point?????????Stack????????????????
- Stack???????????????????(??)??????
- ?????,?????????Stack???!
- ????????(template)
22Stack.h (1 of 3)
????????????,???????class template(????),?????clas
s?typename???????T,?????????????????????
????????????,????????T??????????
23Stack.h (2 of 3)
????stackPtr?????,????T???
??????????????????,???????????????????
??!!??,Stack???????????,???????????StackltTgt,??
24Stack.h (3 of 3)
25Note ? ? ? ? ?
- 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??,??
?????????,????????????????
26fig14_03.cpp (1 of 3)
?????????????????
?????????(class-template specialization),Stackltdou
blegt? ???????double?????T??
27fig14_03.cpp (2 of 3)
?????????(class-template specialization),Stackltint
gt? ???????int?????T??
28fig14_03.cpp (3 of 3)
?????,?????????????,??????Stack???????double?int?
????,?????,????????Stack??????????????,???????????
???????????,???????????
29fig14_04.cpp (1 of 3)
????,??????????????,??StackltTgt????????
????????T,????StackltTgt????????
????????????T?????????,???????????????,??????
??_______________________
30fig14_04.cpp (2 of 3)
3114.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
3214.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
33Exercise
- 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()?
34An 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
35Implementing 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.
36Circular 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
37B
C
A
D
E
H
F
G
How do know whether the queue is empty or full?
38An 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
39Implementing 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.
40Implementing 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.
41Implementing 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.
427.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
437.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.
447.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
45fig07_26.cpp (1 of 6)
??!??vector?????????ltvectorgt???
vectorltintgt????????,????????????
????vector???int??
vector??????????size,???????????
46fig07_26.cpp (2 of 6)
???????vector????????????_______??!????
???????vector????????,??????????????????_______??_
________
47fig07_26.cpp (3 of 6)
vector???????,?????????????????????????????????
??at()?????????????????????????????
48fig07_26.cpp (4 of 6)
49Execution Result
fig07_26.cpp (5 of 6)
50Execution Result
fig07_26.cpp (6 of 6)
??????,at()????????