1 / 18

Template Structures

Template Structures. Eric Roberts CS 106B February 11, 2013. Contest Results. The CS106B Random Writer Contest February 2013. Honorable Mention: Brad Girardeau (Word-Based Tom Sawyer) . Honorable Mention: Alexander Hsu (Hamlet with Semantics).

ivrit
Download Presentation

Template Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Template Structures Eric Roberts CS 106B February 11, 2013

  2. Contest Results The CS106B Random Writer Contest February 2013 Honorable Mention: Brad Girardeau (Word-Based Tom Sawyer) Honorable Mention: Alexander Hsu (Hamlet with Semantics) Honorable Mention: Alan Kaptanoglu (Paradise Lost) Honorable Mention: Annette Mullaney (Sky High)

  3. Shakespearean Sonnets Awakes my heart; So true a fool is love, thus shall excuse my jade,— A crow that flies in heaven’s sweetest air. So shall I live, as a dream. When wasteful war shall statues overturn, And darkly bright, are themselves as stone, Unmoved, cold, and times of your memory. ’Gainst death, and lusty leaves quite gone, But when my glass shows me myself indeed Beated and chopp’d with tanned antiquity, Mine eye my heart think that we before have heard them told. LXXVII Thy merit hath my pen, —As ’twixt vows, and he in them I read; And needy nothing trimm’d in jollity, And sable curls, all bare, is of my speaking breast. Runner-Up #1 — Allan Raventos

  4. Winds of Democracy And the winds of the north, from the great lakes, and all the weapons of tyrants let loose, but it will certainly come in use; when the fire-flashing guns have fully alerted me, and play with the measureless light. Child: father what is that you express in your eyes? It seems to me there are other men in other lands yearning and thoughtful, it seems to me if i could be content with all if i thought them their own finale? This now is too lamentable a face for a man, and i looking up at the stars, and of each of us inevitable; each of us, for those being born. Democracy! Runner-Up #2 — Tri Dao

  5. Chicken-Heart Tom breath would live near Tallapoosa’s were thrust from it passed on Coosa’s homesick that was no answer TOM dodged for us all comb me becuz I never budged finished and then added: Poor Huck Finn’s finally asked—dimly dreading Ben’s were thrown into secondary importance humiliated and all this If you got your Nance by a little by Tom lay waiting anxiety like But at his name they turn his moiety on the cussed smothery houses Who art said go out of himself —chicken-heart Runner-Up #3 — Tommy Truong

  6. Bob Dylan’s Random Writer Blues F Em/b Well, he peak of the sun ’cause tonight Dm F an’ we gazed upon the road, C Am make promised that seaport town C F called on me to you F Em/b with a pain that i could not feel so sad. Dm F dead man, C Am when i’m all alone one nights; C F forty-one days, all igotta take a change possessed F C by no special all right G A and cast off like crossin’ the bay of mexico C Em/b fanning to do whatever young, G D forever you gotta do is survive, F Em/b Well, he’s a weird monkey, very funky. Dm F i said for his age, he’s wild C Am my only prayer for him in the children C F who could give, F Em/b we walked together, Dm F we’ll climb that hill no matter what gets in the dark does die C Am as the monks C F the c.i.o. F C by no special all right G A and cast off like crossin’ the bay of mexico C Em/b fanning to do whatever young, G D forever you gotta do is survive, F Em/b Well, tell me no lies. Dm F are you one questions burning of the hangin’ on the bowery slums C Am to those clothes and you’ll come baby, here’s too many books C F she gone with a golden rule. F Em/b you always right Dm F on a night long C Am listenin’ for the wheel, took off her when he said, "that’s mine." C F joey, joey, F C by no special all right G A and cast off like crossin’ the bay of mexico C Em/b fanning to do whatever young, G D forever you gotta do is survive First Place — Jack Maris

  7. Midterm Histogram N = 388 Median = 53.0/60 Mean = 50.3/60 64 109 35 33 44 27 19 16 10 23 8 59–60 55–58 53–54 51–52 47–50 44–46 41–43 37–40 34–36 25–33 00–24 A+ A A– B+ B B– C+ C C– D NP

  8. Templates • One of the most powerful features in C++ is the template facility, which makes it possible to define functions and classes that work for a variety of types. • The most common form of a template specification is template <typename placeholder> where placeholder is an identifier that is used to stand for a specific type when the definition following the template specification is compiled.

  9. Templates in Functions • Templates can be used before a function definition to create a generic collection of functions that can be applied to values of various types. • The following code, for example, creates a template for the max function, which returns the larger of its two arguments: template <typenameValueType> ValueTypemax(ValueType v1, ValueType v2) { return (v1 > v2) ? v1 : v2; } • The compiler will generate the code for many different versions of max, one for each type that the client uses. • The function max can be used only with types that implement the > operator. If you call max on some type that doesn’t, the compiler will signal an error.

  10. void sort(int array[], intn) { for (intlh = 0;lh < n;lh++) { intrh = lh; for (inti=lh + 1;i< n;i++) { if (array[i] < array[rh])rh = i; } swap(array[lh], array[rh]); } } void swap(int & x, int & y) { inttmp = x; x = y; y = tmp; } Exercise: Rewrite sort as a Template • Rewrite the following code so that it sorts any type that implements the < operator:

  11. Templates in Class Definitions • Templates are more commonly used to define generic classes. When they are used in this way, the template keyword must appear before the class definition and before each of the implementations of the member functions. • The most inconvenient aspect of using templates to create generic classes is that the compiler cannot process them correctly unless it has access to both the interface and the implementation at the same time. The effect of this restriction is that the .h files for template classes must contain both the prototypes and the corresponding code. • To emphasize the conceptual separation between the interface and the associated implementation, you should make sure to include an appropriate comment before the private section and the implementation warning casual clients away from the details.

  12. Once you have made this change, each instance of the specific type (formerlychar in theCharStackclass) must be replaced by theValueTypeplaceholder for the generic type, as in ValueType *elements; or voidpush(ValueTypevalue); A Template Version of theStackClass • The first step in writing the template version of theStackclass is to add the template keyword to the interface just before the class definition: template <typenameValueType> class Stack { . . . body of the class . . . };

  13. Implementing the Template Class • The final change necessary to implement the template class is to add template declarations to every method body, as in the following updated version of the constructor: template <typenameValueType> Stack<ValueType>::Stack() { capacity = INITIAL_CAPACITY; count = 0; elements = newValueType[capacity]; } • Because of the restrictions that C++ imposes on template types, the implementations of the methods need to be included as part of thestack.h header.

  14. Assignment and Copy Constructors • There is one remaining issue about creating new abstract classes that is extremely important in practice, which is how such objects behave if you copy them using assignment or by passing them by value to parameters in methods. • The crux of the problem is that copying an abstract data object typically needs to copy the underlying data and not just the fields directly accessible in the object. Unfortunately, the default interpretation in C++ is to copy only the top-level fields, which can lead to serious errors. • Even though the text includes an extensive discussion of the issues surrounding assignment and copy constructors, we won’t hold you responsible for these topics in CS106B. If, however, you are applying for a job that requires you to use C++, you absolutely need to review this material.

  15. 10 1000 elements 1000 100 20 capacity 3 30 count . . . 1000 elements 100 capacity 3 count 10 2000 elements 2000 20 100 capacity 30 3 count . . . Shallow vs. Deep Copying • Suppose that you have a Stack<int> containing three elements as shown in the diagram to the right. • A shallow copy allocates new fields for the object itself and copies the information from the original. Unfortunately, the dynamic array is copied as an address, not the data. • A deep copy also copies the contents of the dynamic array and therefore creates two independent structures

  16. Implementing Deep Copy Semantics • When you are defining a new abstract data type in C++, you typically need to define two methods to ensure that copies are handled correctly: • The operator operator=, which takes care of assignment • A copy constructor, which takes care of by-value parameters • These methods have well-defined signatures and structures, and the easiest thing to do is simply to copy the code on the next slide, adapting it as necessary to account for the specific instance variables that need to be copied in the underlying representation.

  17. Code to Implement Deep Copying /* Code to support deep copying for the Stack class */ template <typenameValueType> Stack<ValueType>::Stack(const Stack & src) { deepCopy(src); } template <typenameValueType> Stack<ValueType> & Stack<ValueType>::operator=(const Stack & src) { if (this != &src) { if (elements != NULL) delete[] elements; deepCopy(src); } return *this; } template <typenameValueType> void Stack<ValueType>::deepCopy(const Stack & src) { count = capacity = src.count; elements = (capacity == 0) ? NULL : new ValueType[capacity]; for (inti = 0; i < count; i++) { elements[i] = src.elements[i]; } }

  18. The End

More Related