Part E - Polymorphism

Function Templates

Workshop 10

In this workshop, you code a template for sorting variables or objects of any type.

Learning Outcomes

Upon successful completion of this workshop, you will have demonstrated your abilities to

• code a function template
• code an explicit specialization for a function template

Sort - All Groups

Definition

Code a function that bubble sorts an array of ints that contains n elements.  Your function sorts the elements in ascending order from lower to higher values.  Its prototype is

 void sort(int* a, int n);

Template

Store a template for your function is a header file named sort.h

Explicit Specialization

Code an explicit specialization of your template for C-style null-terminated strings.

Client Module

The main program that uses your implementation is listed on the left, while the results are shown on the right:

 // Workshop 10 - Sort // w10.cpp #include #include "sort.h" int main() { int a[] = {1234, 546, 786, 2341}; char* c[6] = {"Harry", "Jane", "Anne", "John"}; sort(a, 4); sort(c, 4); for (int i = 0; i < 4; i++) std::cout << a[i] << std::endl; std::cout << std::endl; for (int i = 0; i < 4; i++) std::cout << c[i] << std::endl; std::cout << std::endl; } 546 786 1234 2341 Anne Harry  Jane John

Typescript

Create a typescript of your complete solution using the following commands:

 + At the prompt, type: script w10.txt + At the prompt, type: whoami + At the prompt, type: cat sort.h + At the prompt, type: g++ -o w10 w10.cpp  + At the prompt, type: w10 + At the prompt type: exit

Sort Fractions - Group Y

Code the template for the sort() function as described above.  Upgrade your Fraction class from Workshop 6 by overloading the > operator for comparison of objects of that class.

Client Module

The main program that uses your implementation is listed on the left, while the results are shown on the right:

 // Workshop 10 - Sort // w10.cpp #include #include "Fraction.h" #include "sort.h" int main() { Fraction f[4]; f[0] = Fraction(4, 6); f[1] = Fraction(3, 9); f[2] = Fraction(24, 48); f[3] = Fraction(17, 33); sort(f, 4); for (int i = 0; i < 4; i++) { f[i].display(); std::cout << std::endl; } } 1/3 1/2 17/33  2/3

Typescript

Create a typescript of your complete solution using the following commands:

 + At the prompt, type: script w10.txt + At the prompt, type: whoami + At the prompt, type: cat sort.h Fraction.h Fraction.cpp  + At the prompt, type: g++ -o w10 w10.cpp Fraction.cpp + At the prompt, type: w10 + At the prompt type: exit

SUBMISSION

Moodle

• Select W10 under Assignments and Tasks
• Write a short note to your instructor
• press "Edit"
• press "Save Changes"
• When ready to submit, press "Send for Marking"

Other Submissions