Templates and Friends - PowerPoint PPT Presentation

1 / 49
About This Presentation
Title:

Templates and Friends

Description:

Templates and Friends Lesson #9 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek – PowerPoint PPT presentation

Number of Views:145
Avg rating:3.0/5.0
Slides: 50
Provided by: CIS4117
Category:

less

Transcript and Presenter's Notes

Title: Templates and Friends


1
Templates and Friends
  • Lesson 9

Note CIS 601 notes were originally developed by
H. Zhu for NJIT DL Program. The notes were
subsequently revised by M. Deek
2
Content
  • Function template
  • Class template
  • Friends

3
Templates
  • Templates give us the means of defining a family
    of functions or classes that share the same
    functionality but which may differ with respect
    to the data type used internally.
  • A class template is a framework for generating
    the source code for any number of related
    classes.
  • A function template is a framework for generating
    related functions.

4
Function Templates
  • A function can be defined in terms of an
    unspecified type.
  • The compiler generates separate versions of the
    function based on the type of the parameters
    passed in the function calls.

5
Function Template
  • template ltclass Tgt
  • return-type function-name(T param)
  • //one parameter function.
  • T is called a template parameter.

6
One parameter function template
  • template ltclass Tgt
  • void Display(const T val)
  • cout ltlt val
  • One parameter function with an additional
    parameters which are not template parameters
  • template ltclass Tgt
  • void Display(const T val, ostream os)
  • os ltlt val
  • The same parameter appear multiple times.
  • template ltclass Tgt
  • void Swap(T x, T y)
  • ... // Example ex9swap.cpp

7
Swap
swap Function Template
generic
...
Swap 2 integers
Swap 2 floats
Swap 2 rationales
...
8
Swap
  • include ltiostream.hgt
  • template ltclass TParamgt
  • void Swap( TParam x, TParam y )
  • TParam temp
  • temp x
  • x y
  • y temp

9
Swap
  • class Student
  • public
  • Student( unsigned id 0 )
  • idnum id
  • int getID() return idnum
  • private
  • unsigned idnum

10
Swap
  • int main()
  • int m 10
  • int n 20
  • Student S1( 1234 )
  • Student S2( 5678 )
  • cout ltlt mltlt" "ltltnltlt" "ltltendl
  • Swap( m, n ) // call with integers
  • cout ltlt mltlt" "ltltnltlt" "ltltendl
  • cout ltlt S1.getID()ltlt" "ltltS2.getID()ltlt"
    "ltltendl
  • Swap( S1, S2 ) // call with Students
  • cout ltlt S1.getID()ltlt" "ltltS2.getID()ltlt"
    "ltltendl
  • return 0

11
Multiple parameter function template
  • template ltclass T1, T2gt
  • void ArrayInput(T1 array, T2 count)
  • for (T2 j 0 j lt count j)
  • cout ltlt value
  • cin gtgt arrayj

12
Multiple parameter function template
  • const unsigned tempCount 3
  • float temperaturetempCount
  • const unsigned stationCount 4
  • int stationstationCount
  • ArrayInput(temperature, tempCount)
  • ArrayInput(station, stationCount)

13
Table Lookup
  • include ltiostream.hgt
  • template ltclass Tgt
  • long indexOf( T searchVal, const T table,
    unsigned size )
  • for( unsigned i0 i lt size i )
  • if( searchVal tablei )
  • return i
  • return -1

14
Table Lookup
  • int main()
  • const unsigned iCount 10
  • const unsigned fCount 5
  • int iTableiCount 0,10,20,30,40,50,60,70,80
    ,90
  • float fTablefCount 1.1, 2.2, 3.3, 4.4,
    5.5
  • cout ltlt indexOf( 20, iTable, iCount ) ltlt endl
    // "2"
  • cout ltlt indexOf( 2.2f, fTable, fCount ) ltlt
    endl // "1"
  • const unsigned sCount 5
  • char namessCount "John","Mary","Sue","Da
    n","Bob"
  • cout ltlt indexOf( "Dan", names, sCount )ltltendl
    // ?
  • return 0
  • //ex9funtemplate.cpp

15
(No Transcript)
16
Note
  • In a function template, if an operator is used,
    you must be sure every class relevant to the
    template will support the operator (such as ,
    etc.).
  • C provides the mechanism of operator
    overloading to ensure compatibility.

17
Student
  • class Student
  • public
  • Student( long idVal )
  • id idVal
  • int operator ( const Student s2 ) const
  • return id s2.id
  • private
  • long id // student ID number

18
Student
  • int main()
  • const unsigned sCount 5
  • Student sTablesCount 10000, 11111, 20000,
    22222, 30000
  • Student s( 22222 )
  • cout ltlt indexOf( s, sTable, sCount )ltltendl
    // print "3"
  • return 0
  • //ex9student.cpp

19
(No Transcript)
20
Overriding a Function Template
  • When a function template does not apply to a
    particular type, it may be necessary to either
  • override the function template, or
  • make the type conform to the function template.

21
Explicit Function Implementation
  • long indexOf( const char searchVal, char
    table,
  • unsigned size )
  • for(unsigned i 0 i lt size i)
  • if( strcmp(searchVal, tablei) 0 )
  • return i
  • return -1

22
Explicit
  • int main()
  • const unsigned iCount 10
  • const unsigned nCount 5
  • int iTableiCount 0,10,20,30,40,50,60,70,80
    ,90
  • cout ltlt indexOf( 20, iTable, iCount ) ltlt
    endl//2
  • char namesnCount "John","Mary","Sue","Da
    n","Bob"
  • cout ltlt indexOf( "Dan", names, nCount
    )ltltendl//3
  • return 0
  • //ex9expicit.cpp

23
(No Transcript)
24
Class Template
  • Declare and define an object
  • template ltclass Tgt
  • class MyClass
  • //...
  • MyClass ltintgt x
  • MyClass ltstudentgt aStudent

25
A Simple Example
  • template ltclass T1, class T2gt
  • class Circle
  • //...
  • private
  • T1 x, y
  • T2 radius
  • //...
  • Circle ltint, longgt c1
  • Circle ltunsigned, floatgt c2

26
Class Template
27
Array Class Template
  • template ltclass Tgt
  • class Array
  • public
  • Array( unsigned sz )
  • Array()
  • T operator( unsigned i )
  • private
  • T values
  • unsigned size

28
Array Class Template
  • templateltclass Tgt ArrayltTgtArray( unsigned sz )
  • values new T sz
  • size sz
  • templateltclass Tgt T ArrayltTgtoperator (
    unsigned i )
  • if( i gt size )
  • throw RangeError(__FILE__,__LINE__,i)
  • return valuesi
  • templateltclass Tgt ArrayltTgtArray()
  • delete values

29
Array Class Template
  • int main()
  • const unsigned numDives 2
  • Arrayltintgt diveNum( numDives )
  • Arrayltfloatgt difficulty( numDives )
  • ArrayltFStringgt diveName (numDives)
  • int j
  • for(j 0 j lt numDives j)
  • cout ltlt "Enter dive , difficulty level, dive
    name "
  • cin gtgt diveNumj gtgt difficultyj gtgt ws
  • diveNamej.GetLine( cin )
  • for(j 0 j lt 2 j)
  • cout ltlt diveNamej ltlt '\n'
  • cout ltlt endl
  • return 0
  • //cis601course/chap10/array/array.cpp

30
(No Transcript)
31
Templates and Inheritance
  • A template is not a class
  • A template is not inherited
  • A class based on a template is an ordinary class
  • class t1 public Arrayltintgt
  • ...//OK!!!
  • templat ltclass Tgt
  • class Myclass public aClass
  • //OK!!!

32
Templates and static members
  • Remember
  • Template is not class.
  • Static members defined in a template are static
    members of the classes associated with a template.

33
Friends
  • Friend classes
  • Friend functions

34
Friend classes
  • A friend class is a class in which all member
    functions have been granted full access to all
    the(private, protected, and certainly public)
    members of the class defining it as a friend (by
    instances).
  • The friend class is defined inside the class
    granting friendship.

35
Example
include ltiostream.hgt include ltstring.hgt class
Student class Employee char id8 // ID
number float payRate // pay rate public
Employee( char idVal ) strcpy( id,
idVal) id7 0 payRate 0.24f
friend class Student
  • class c1
  • friend c2
  • //...
  • class c2
  • friend c3
  • //...

36
Example
  • class Student
  • char id8 // ID number
  • public
  • Student()
  • id0 '\0'
  • employed 0
  • void getE1()
  • Employee e("xxxxxxx")
  • cout ltlte.idltltendl ltlte.payRateltltendl
  • void getE2(Employee e)
  • cout ltlte.idltltendl ltlte.payRateltltendl

void main() Employee E( "333445555" )
Student S S.getE1() S.getE2(E) //ex9cfrien
d.cpp
37
(No Transcript)
38
Friend functions
  • A friend function is a function which has been
    granted full access to the private and protected
    members of an instance of the class.
  • The friend function is defined inside the class
    granting friendship.

39
Example
  • include ltiostream.hgt
  • include ltstring.hgt
  • class Student // forward declaration required
  • class Employee
  • enum idMax 9
  • char ididMax1 // ID number
  • float payRate // pay rate
  • public
  • Employee( char idVal )
  • friend void hirestudent( Student S, Employee
    E, float rate )

40
Example
  • class Student
  • enum idMax 7
  • char ididMax1 // ID number
  • int employed // 1 employed, 0 not
    //employed
  • public
  • Student( char idVal )
  • friend void hirestudent( Student S, Employee
    E, float rate )

41
Example
  • EmployeeEmployee( char idVal )
  • strncpy( id, idVal, idMax)
  • ididMax '\0'
  • payRate 0.0
  • StudentStudent( char idVal )
  • strncpy( id, idVal, idMax )
  • ididMax '\0'
  • employed 0

42
Example
  • // Global function that is a friend of both
    classes.
  • void hirestudent( Student S, Employee E,
    float rate )
  • S.employed 1
  • E.payRate rate
  • int main()
  • Employee E( "333445555" )
  • Student S( "1234567" )
  • hirestudent( S, E, 12.5 )
  • return 0
  • //ex9employee.cpp

43
(No Transcript)
44
Properties of Friends
  • Non-symmetrical
  • For example If c2 is a friend of c1, but c1 is
    not a friend of c2.
  • Non-transitive
  • For example If c2 is a friend of c1 and c3 is a
    friend of c2, but c3 is not a friend of c1.

45
Properties of Friends
  • Not inheritable
  • A friend of a base class is not inherited by
    derived classes.

46
Example
  • class Employee
  • public
  • friend float CalcPay(Employee E)
  • //..
  • class SalariedEmployee public Employee//...
  • //Here, the function CalcPay() can not access the
    private members of SalariedEmployee!!!

47
Things to consider when using Friends
  • Friends make loosely coupled classes tightly
    coupled, which may results in problems with
    modularity and error searching.
  • Friends diminish encapsulation and information
    hiding.
  • Limit the use of friends.

48
Templates and Friends
  • Friends of a template consist of all the friends
    of the classes associated with the template.

49
Readings
  • Readings
  • Chapter 10
Write a Comment
User Comments (0)
About PowerShow.com