Title: Object-oriented programming with C
1Lesson A
Template Functions
2Lesson A Objectives
- To learn
- How to create template functions
- How to use multiple parameters in a template
function - How to overload template functions
3Lesson A Objectives
- To learn
- How to use more than one type in a template
function - How to explicitly specify the type in a template
function - How to use template functions with class objects
4Creating Template Functions
- Template functions
- Allow you to write a single function that serves
as an outline, or template, for a group of
functions that differ in the types of parameters
they use - In a template function, at least one argument is
generic, or parameterized
5int reverse(int x) return (-x) double
reverse(double x) return (-x) float
reverse(float x) return (-x)
6variableType reverse(variableType x) return
(-x)
7Creating Template Functions
- Before coding a template function, include a
template definition with the following
information - The keyword template
- A left angle bracket (lt)
- A list of generic types, separated with commas if
more than one type is needed - A right angle bracket(gt)
8Creating Template Functions
- A family of functions
- A group of functions that is generated from the
same template - C allows you to define macros, which permit
generic substitution - However, macros are seldom recommended
9templateltclass Tgt T reverse(T x) return
(-x)
double amount-9.86 reverse(amount)
10Creating Template Functions
- Each generic type in the list of generic types
has two parts - The keyword class
- An identifier that represents the generic type
- Although any legal C identifier may be used for
the type in the template function, many
programmers prefer T (for Template)
11Creating Template Functions
- When you call a template function, a generated
function that uses the appropriate type is
created or instantiated - The compiler generates code for as many different
functions as it needs, depending on the function
calls made - The definition of the template function and the
template function itself must reside in the
source file
12Creating Template Functions
- You cant place the function definition and the
function code in separate files because - The function cant be compiled into object format
without knowing the types - The function wont know that it needs to
recognize the types without the template
definition
13includeltiostream.hgt includeltiomanip.hgt includelt
dos.hgt templateltclass Tgt void fillScreen(T
answer) int width5 for (int t0
tlt20t) coutltltsetw(width)ltltanswer
coutltlt"Another Teacher's Pet Sucess"ltltendl
widthwidth2
14 void main() int iUseAns, iCorrectAns11 cou
tltlt"What is 47?" cingtgtiUseAns if(iUseAnsiCo
rrectAns) fillScreen(iUseAns)
15Using Multiple Parameters and Overloading
Function Templates
- Function templates may have more than one
parameter - You may overload function templates, as long as
each version of the function takes different
arguments, allowing the compiler to distinguish
between them
16includeltiostream.hgt templateltclass Tgt T
larger(T x, T y) T big if (xgty)
bigx else bigy return(big)
17void main() int a7, b12 double c4.5,
d1.3 coutltltlarger(a,b)ltltendl coutltltlarger(c,d)lt
ltendl // coutltltlarger(a,c) errors
Overloading example
18includeltiostream.hgt templateltclass Tgt void
inverse(T x, T y) T temp tempx
xy ytemp templateltclass Tgt void
inverse(T x) x-x
19 void main() double d13.4, d25.6 inverse(d1)
inverse(d1,d2) coutltltd1ltlt" "ltltd2ltltendl
20Using More Than One Type in a Template Function
- To create a template function that employs
multiple types, you simply use a unique type
identifier for each type - The option of using multiple types in a template
function may not be available on some older C
compilers
21includeltiostream.hgt template ltclass T, class
Ugt void firstLarger(T val1, U val2) if (val1
gtval2) coutltlt"First is larger"ltltendl
else coutltlt"First is not larger"ltltendl v
oid main() firstLarger(2.1, 9) firstLarger('G',
12)
22Explicitly Specifying the Type in a Template
Function
- When you call a template function, the arguments
to the function dictate the types to be used - To override deduced types, you can explicitly
code types within angle brackets immediately
following the function name in the function call - You can code empty angle brackets after the
function name to indicate the types should be
deduced and not overridden
23Explicitly Specifying the Type in a Template
Function
- Explicitly specifying a type is particularly
useful when at least one of the types you need to
parameterize or generate within the function is
not an argument to the function - The compiler can deduce the template function
types only by using the values passed to the
function
24includeltiostream.hgt templateltclass Tgt T
reverse(T x) return (-x) void main()
double amount45.65 coutltltreverse(amount)
coutltltreverseltdoublegt(amount)
25includeltiostream.hgt templateltclass T, class Ugt T
reverse (U x) return (-x) void main()
double amount-8.8 coutltltreverseltintgt(amount)
coutltltreverseltdoublegt(amount)ltltendl
coutltltreverseltintgt(amount)ltltendl
coutltltreverseltint,doublegt(amount)ltltendl
26Using Template Functions with Class Objects
- Template functions work as well with classes as
they do with simple data types - Your additional responsibility is to
- Ensure that any operations used within the
template function have been defined for the class
objects passed to the template functions
27includeltiostream.hgt templateltclass Tgt T
reverse(T x) return (-x) class
PhoneCall private int lengthOfCall
char billCode public
28PhoneCall(const int l, const char b)
PhoneCall PhoneCalloperator-(void) void
showCall(void) PhoneCallPhoneCall(const
int len0, const char b' ') PhoneCalllengthOf
Calllen PhoneCallbillCodeb void
PhoneCallshowCall(void) coutltlt"the code is
"ltltPhoneCallbillCodeltltendl
29PhoneCall PhoneCalloperator-(void)
PhoneCallbillCode'C' return
(this) void main() PhoneCall aCall(10,
'S') aCall.showCall() aCallreverse(aCall) a
Call.showCall()
30Lab Exercises and Homework
- Do Exercises 1 on page 347
- Do Exercises 2 on page 347
- Do Exercises 3 on page 347
- Due date
31Lesson B
Template Classes
32Lesson B Objectives
- To learn
- The advantages of using template classes
- How to create a complete class template
- How to create container classes
33Template Classes
- If you find it necessary to create several
similar classes, you might consider developing a
template class - Template class
- Class in which at least one type is generic or
parameterized - It provides the outline for a family of similar
classes
34Template Classes
- To create a template class
- Begin with the template definition
- Then write the class definition using the generic
type or types in each instance for which a
substitution should take place
35Template Classes
- Within a program, you can instantiate objects
that have the class template type - Add the desired type to the current class
instantiation by placing its name between angle
brackets following the generic class name
36templateltclass Tgt class Number private T
theNumber public Number(const T n)
void display(void)
Numberltintgt myValue
NumberltintgtmyValue(77)
Numberltdoublegt yourValue(3.46) yourValue.display(
)
myValue.display()
37Creating a Complete Class Template
- To use a template class member function, you use
the dot operator with an instantiation of the
class - Some C programmers reserve the term class
template to indicate the source code they write,
using template class to refer to the actual
generated class that exists for a specific type
after C determines what type applies
38includeltiostream.hgt templateltclass Tgt class
Generic private T instance
public Generic(T i) void
print(void)
39//generic constructor templateltclass
Tgt GenericltTgtGeneric(T i0) Genericinstance
i templateltclass Tgt void GenericltTgtprint(vo
id) coutltlt"Generic orinting
"ltltendl coutltltGenericltTgtinstanceltltendl
40 class Employee private int
idNum double salary public Employee(int
id) friend ostream operator
ltlt(ostream out, const Employee e)
41EmployeeEmployee(int id0) EmployeeidNumid
Employeesalary4.9 ostream
operatorltlt(ostream out, const Employee emp)
outltlt"Employee number "ltltemp.idNum outltlt"
Salary "ltltemp.salary return(out)
42void main() GenericltintgtanInt(7) Genericltdoub
legtsomeMoney(6.65) GenericltEmployeegt
aWorker(333) anInt.print() someMoney.print()
aWorker.print()
43Container Classes
- Many C compilers come with class libraries
called container classes - Container classes
- Template classes that have already been written
to perform common class tasks - The purpose of container classes is to manage
groups of other classes
44Container Classes
- A common programming task is to create a linked
list - Linked list
- Chain of objects, each of which consists of at
least two parts - An object
- A pointer to another object
45Container Classes
- Many linked lists provide more than a pointer to
the next logical object - No matter what types of objects are linked,
procedures must be developed to - Establish links between objects
- Insert new member objects into appropriate spots
within the linked list
46Container Classes
- A generic class that holds an object and a link,
plus all linked list functions that handle the
lists chores, is a useful tool when working with
lists - As such a class may be used with a number of
other class objects - The developers of C have already created such a
container class - Its name is List
47Container Classes
- List
- Contains functions like add(), detach(), and
getItem() - List is a template class because the programmers
who designed your compiler could not have
predicted the exact characteristics of all
classes you might create
48Container Classes
- Different compilers include different built-in
classes - Some compilers may not offer any container
classes - The more container classes your compiler
supplies, the less you may find it necessary to
write your own template classes - Nevertheless, it is still beneficial to
understand how its done
49includeltiostream.hgt templateltclass Tgt class
Array private T data int size
public Array(T d, int s) void
showList(void) void showFirst(void)
50template ltclass Tgt ArrayltTgtArray(T d, int s)
ArrayltTgtdatad ArrayltTgtsizes
templateltclass Tgt void ArrayltTgtshowList()
int szArrayltTgtsize coutltlt"Entire List
"ltltendl for(int x0 xltsz x)
coutltltArrayltTgtdataxltltendl
51templateltclass Tgt void ArrayltTgtshowFirst()
coutltlt"First element is " coutltltArrayltTgtdata
0ltltendl class Employee private int
idNum double salary public Employee(int
id) friend ostream operator
ltlt(ostream out, const Employee e)
52EmployeeEmployee(int id0) EmployeeidNumid
Employeesalary4.9 ostream operator
ltlt(ostream out, const Employee
emp) outltlt"Employee number
"ltltemp.idNum outltlt" Salary "ltltemp.salary retur
n(out)
53void main() int vals422,33,44,55
Arrayltintgtval(vals, sizeof(vals)/sizeof(vals0))
Employee workers6110, 220, 330, 440,
550, 660 ArrayltEmployeegt worker(workers,
sizeof(workers)/sizeof(workers0))
val.showList() val.showFirst()
worker.showList() worker.showFirst()
54Lab Exercises and Homework
- Do Exercises 1 on page 358
- Do Exercises 2 on page 358
- Do Exercises 3 on page 358
- Due date