150 chapter 9 t emplates and con tainers define the
play

150 Chapter 9 T emplates and Con tainers Define The - PDF document

150 Chapter 9 T emplates and Con tainers Define The template mec hanism in C is p erhaps one of the more complex features of the language ++ A that has no corresp ondence in Ja v a. T emplates allo w class


  1. 150

  2. Chapter 9 T emplates and Con tainers Define The template mec hanism in C is p erhaps one of the more complex features of the language ++ A that has no corresp ondence in Ja v a. T emplates allo w class de�nitions or functions to b e template al lows a class parameterized b y t yp es or v alues, in m uc h the same w a y that a function de�nition can or function to b e executed with a v ariet y of di�eren t v alues. The template mec hanism is p erformed at b e p ar ameter- compile time, and p ermits a great deal of t yp e c hec king to b e p erformed statically , and ize d by a typ e eliminates man y of the run-time casts that t ypically p opulate Ja v a programs (and consume Ja v a execution time). A ma jor use of templates is as a to ol to dev elop a ric h set of data structure, or con tainer abstractions. In this c hapter w e will �rst explain the template mec hanism, con trasting it with v arious di�eren t tec hniques in Ja v a. The c hapter will then conclude with a description of the Standard T emplate Library , or STL. The STL is the ma jor data structure library used b y C programs. ++ 9.1 T emplate Classes T emplate classes are p erhaps b est explained using an example. Consider the follo wing de�- nition, whic h is a generalization of the b o x data structure w e dev elop ed in earlier c hapters: template <class T> class box f public: f g box ( ) box (T v) : val(v) f g f g box (box<T> & right) : val(right.val) T value() f return val; g 151

  3. 152 CHAPTER 9. TEMPLA TES AND CONT AINERS f g void operator = (T right) val = right; void operator = (box<T> & right) f val=right.val; g private: T val; g ; The new b o x is a template class. That means that the t yp e b o x itself is incomplete, it cannot b y itself b e used to create instances. Instead, the parameter ( T , in this case) m ust b e �lled in with a sp eci�c t yp e b efore an instance can b e created. A class template giv es the programmer the abilit y to de�ne a data t yp e in whic h some t yp e information is purp osely left unsp eci�ed, to b e �lled in at a later time. One w a y to think of this is that the class de�nition has b een parameterized in a manner similar to a pro cedure or function. Just as sev eral di�eren t calls on the same function can all pass di�eren t argumen t v alues through the parameter list, di�eren t instan tiations of a parameterized class can �ll in the t yp e information in di�eren t w a ys. Within the class b o dy the v ariable T can b e used as a t yp e name. Th us, w e can declare v ariables of t yp e T , ha v e functions that return a T v alue, and so on. (Note that T is simply an iden ti�er, and that an y other iden ti�er name could ha v e b een used.) T o create an ob ject w e m ust �rst sp ecify a v alue for T . F or example, the follo wing creates a b o x that will hold an in teger, and a b o x that will hold a double precision v alue: box<int> ib; box<double> db; ib = 7; db = 3.14; box<int> ibtwo = 4; // can b e initialized in constructor ib = ibtwo; int x = ib.value(); The t yp es asso ciated with template classes are scrupulously c hec k ed at compile time. An attempt to use a v alue incorrectly will result in a compile time error: ib = 2.7; // error - cannot assign real to in t Probably the most common use for template classes, although b y no means the only one, is to create con tainer classes. The STL, describ ed in Section 9.3, is one suc h collection of classes. F or example, the list data structure represen ts the abstraction of a link ed list, but do es not itself sp ecify the particular t yp e of elemen ts it will con tain. Instead, the elemen t t yp e is sp eci�ed b y a template parameter: create a list of in tegers list<int> ilist; //

  4. 9.1. TEMPLA TE CLASSES 153 create a list of real n um b ers list<double> dlist: // � > create a list of p oin ters to animals list<Animal alist; // ilist.push front(7); // add an elemen t to fron t of list int x = ilist.front(); // extract �rst elemen t from list Con trast this with the w a y collections are implemen ted in Ja v a. In Ja v a, the v alues held b y a collection class are stored in v ariables declared as Object . There are t w o ma jor problems with the Ja v a approac h: 1. It means that non ob ject v alues, suc h as primitiv e t yp es (in teger and the lik e) cannot b e stored in Ja v a collections. This is the ma jor reason the Ja v a language pro vides wrapp er classes, suc h as Integer . 2. It means that when a v alue is remo v ed from a Ja v a collection, it m ust b e cast bac k to the appropriate t yp e. Notice that there are no cast op erations in the ab o v e example. When w e remo v e an elemen t from the list ilist , the compiler kno ws already that it is an in teger, and not a double or an animal or an y other sort of v alue. By using templates, the language allo ws truly reusable, general-purp ose comp onen ts to b e created and manipulated with a minim um of di�cult y and y et still retain t yp e safet y , whic h is an imp ortan t goal of strongly t yp ed languages. On the other hand, Ja v a can easily main tain heterogeneous collections, that is, collections of v alues of v arious di�eren t t yp es. Suc h collections are more di�cult to represen t in C . ++ The k eyw ord class in the template parameter list is somewhat misleading, since the v alue Note can b e an y t yp e quan tit y , not simply a class v alue. (The sligh tly more descriptiv e k eyw ord The t yp ename can b e used instead of class , ho w ev er this is a recen t c hange to C and as y et not keywor d t yp e- ++ name is a r e- supp orted b y man y compilers). F or example, w e created b o x v alues using the int t yp e as a c ent addition template parameter, whic h is not a class t yp e. Other primitiv e v alues can also b e used as to the C ++ template parameters. F or example, the follo wing creates a bit arra y with a giv en n um b er language of bit v alues. f template <int s> class bitSet public: set (int index) f ... g test (int index) f ... g void operator = (bitSet<s> & right); protected: assume 16 bits p er w ord // int data [ (s + 15)/ 16 ];

  5. 154 CHAPTER 9. TEMPLA TES AND CONT AINERS g ; T o manipulate a bit arra y w e simply �ll the template argumen t v alue with an in teger quan tit y: bitSet<25> a; a.set(17); // set p osition 17 if (a.test(i)) ... A bit arra y can b e assigned to another bit arra y of the same size, but not to an arra y with a smaller n um b er of v alues: bitSet<25> b; bitSet<30> c; a = b; // ok, will execute assignmen t op erator a = c; // pro duces compile time error, sizes don't matc h 9.1.1 T emplate Metho ds When template metho ds are written separately from the class de�nition, they m ust also b e b e parameterized b y the template argumen t: template <int s> void bitSet<s>::operat or = (bitSet<s> & right) f // �rst compute the data v ector size int max = (s + 15) / 16; // then cop y all the data �elds in to our arra y for (int i = 0; i < max; i++) data[i] = right.data[i]; g Notice that the class name bitSet has b een quali�ed b y the template argumen t s . This is not simply a metho d in class bitSet , but is a metho d in bitSet < s > . 9.2 T emplate F unctions In addition to classes, ordinary functions can also b e giv en template de�nitions. A simple example is the follo wing, whic h is a function to determine the maxim um of t w o quan tities:

Recommend


More recommend