C++_templates_and_interface_polymorphism_I

C++_templates_and_interface_polymorphism_I - Motivation for...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
CSE 332: C++ template examples Motivation for Generic Programming in C++ We’ve looked at procedural programming Reuse of code by packaging it into functions We’ve also looked at object-oriented programming Reuse of code and data by packaging them into classes However, these techniques alone have limitations Functions are still specific to the types they manipulate E.g., swap (int, int) and swap (int *, int *) do essentially same thing But, we must write two versions of swap to implement both Classes alone are still specific to the types they contain E.g., keep an array (not a vector) of dice and an array of players Must write similar data structures and code repeatedly E.g., adding a new element to an array Generic programming aims to relieve these limitations
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
CSE 332: C++ template examples C++ STL Generic Programming Example #include <iostream> #include <iterator> #include <algorithm> int main (int, const char **) { int numbers [] = {0, 9, 2, 7, 4, 5, 6, 3, 8, 1}; size_t array_dimension = sizeof (numbers) / sizeof (int); // prints out 0 1 2 3 4 5 6 7 8 9 (ascending sort) sort (numbers, numbers + array_dimension); copy (numbers, numbers + array_dimension, ostream_iterator<int>(cout, " ")); cout << endl; // prints out 9 8 7 6 5 4 3 2 1 0 (descending sort) sort (numbers, numbers + array_dimension, greater<int>()); native container type (array) user-defined functor native iterator type (pointer) user-defined iterator type calls to STL algorithms constructor calls
Background image of page 2
CSE 332: C++ template examples Decoupling Data Types from Algorithms STL has an architectural separation of concerns Containers hold data of a particular type Iterators give access to ranges of data Algorithms operate on particular kinds of iterators Functors plug in functions to modify algorithms Containers include arrays, vector , list , set Iterators include pointers, ostream_iterator Algorithms include sort , copy , random_shuffle Functors include less , greater
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
CSE 332: C++ template examples Decoupling Data Types from Algorithms (cont.)
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 12

C++_templates_and_interface_polymorphism_I - Motivation for...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online