

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Various aspects of c++ templates, including function templates that define logic for multiple data types and class templates that create generic class patterns. Topics include function templates for finding maximum values, class templates for memorycell, operator overloading, and function objects. Assumptions and conventions are also discussed.
Typology: Assignments
1 / 2
This page cannot be seen from the preview
Don't miss anything!


These define logic behind the algorithms that work for multiple data types.
These define generic class patterns into which specific data types can be plugged in to produce new classes.
Generic function to find a maximum value in a given vector If argument is a type, then compiler generates a vector
Each call to findMax(Comparable a) on a different data type forces the compiler to generate a different function using the template. Compiler will complain about findMax(v4) because IntCell class does not define operator<
MemoryCell any type Object template can be used for. Assumptions Object constructor has a zero parameter Object has a copy constructor Copy-assignment operator Convention Class templates declaration and implementation usually combined in a single file. It is not easy to separate them in independent files due to complex C++ syntax. This is different from the convention of separating class interface and implementation in different files.
MemoryCell is not a class. It’s a class template. MemoryCell
2 Another example Operator Overloading Defines the meaning of operator< for Employee class. Output operator<< Define a public member function print(ostream &out) Define a global nonclass function operator<< that calls print(…) Function Objects Objects whose primary purpose is to define a function Here findMax() accepts a Comparator function object. parameter as a Comparator assumed to define the isLessThan(Comparator) function. There is a more formal way to define function objects in C++ (next slide). Function objects in C++ style Define operator() for CaseInsensitiveCompare class. Case-sensitive comparison can also be performed using STL function object less Matrices C++ library does not provide a matrix class Constructor Creates zero-sized vectors rows number of Resizes each vector to elements col Two types of [] operators One for LHS that returns by reference Another for RHS that returns by constant reference So we have two very identical functions What makes their signatures different? Reading Assignment for next week 2.1, 2.2, 2.3, 2.4.1, 2.4.2, 2.4.