cs32s10dis5 - CS32: Introduction to Computer Science II...

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

View Full Document Right Arrow Icon
TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Template Classes When we first learned C++, we learned how to define and use variables, and each of these variables had a data type: int , double , char , etc. To allow programmers more flexibility, C++ designers came up with the concept of classes, which is basically a way of defining your own data types. Now we want more flexibility -- each class uses some variables, which have their own types. We want to create a class that works with several different data types. The example on the left is stripped off of the CS31 textbook. The class is simply designed to store an ordered pair of integers. Suppose I also want to come up with a class that stores two doubles. What should I do? The simplest thing would be to “copy and paste” the above code and “find and replace” all int s with double s. What if I also want another “Pair” class with characters? Now you see the problem. The code is going to get bulky, with slightly different versions of the same class with the same functionalities. That is where templates come in to simplify my code. With a template , we can define just one general(template) class that works with different data types. To instantiate an object of this class, you must do the following: Pair<int> p1; Pair<double> p2; where the meanings should be intuitive. One should immediately notice that data structures defined by C++’s STL all take this form, for example: stack<int> s1; queue<double> q1; and now you can sort of predict how they are defined. CS32: Introduction to Computer Science II Spring 2010 Copyright 2010 Brian Choi Week 6, Page 1/4 class Pair { public: Pair(); Pair(int firstValue, int secondValue); void setFirst(int newValue); void setSecond(int newValue); int getFirst() const; int getSecond() const; private: int m_first; int m_second; }; template<typename T> // “template prefix” class Pair { public: Pair(); Pair( T firstValue, T secondValue); void setFirst( T newValue); void setSecond( T newValue);
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/09/2012 for the course CS 32 taught by Professor Davidsmallberg during the Spring '08 term at UCLA.

Page1 / 4

cs32s10dis5 - CS32: Introduction to Computer Science II...

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

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