CS 11 C track: lecture 7 - PowerPoint PPT Presentation

About This Presentation
Title:

CS 11 C track: lecture 7

Description:

Title: CS 11 C track: lecture 1 Author: mvanier Last modified by: Michael Vanier Created Date: 4/5/2003 1:39:46 AM Document presentation format: On-screen Show – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 11
Provided by: mva85
Category:
Tags: lecture | mike | track

less

Transcript and Presenter's Notes

Title: CS 11 C track: lecture 7


1
CS 11 C track lecture 7
  • Today
  • Templates!

2
Templates motivation (1)
  • Lots of code is generic over some type
  • Container data types
  • List of integers, doubles, strings
  • Sparse matrix of ints, doubles, complex
  • How do we handle this?

3
Templates motivation (2)
  • Could write multiple similar classes
  • IntList, FloatList, DoubleList
  • But would be almost identical
  • except for types
  • Adding new method means modifying many files
  • There has to be a better way...

4
Templates motivation (3)
  • Instead can write template classes
  • Listltintgt, Listltdoublegt, Listltstringgt
  • SparseVectorltintgt, SparseVectorltdoublegt
  • Re-use same code for different types

5
Templates example (1)
  • template lttypename Tgt
  • class Array
  • private
  • int len_
  • T data_
  • int check(int i) const
  • if(i lt 0 i gt len_)
  • throw stdstring(out of range!)
  • return i
  • // continued on next slide...

6
Templates example (2)
  • public
  • Array(int len0) len_(len), data_(new
    Tlen)
  • Array() delete data_
  • int len() const return len_
  • T operator(int i) const return
    data_check(i)
  • Array(const Array)
  • Array operator(const Array)

7
Templates example (3)
  • // still in Array.hh
  • // Copy constructor
  • template lttypename Tgt inline
  • ArrayltTgtArray(const ArrayltTgt other)
  • len_(other.len_), data_(new Tother.len_)
  • for (int i 0 i lt len_ i)
  • data_i other.data_i
  • // operator left as exercise...

8
Templates example (4)
  • // testArray.cc
  • include ltiostreamgt
  • include ltstringgt
  • include Array.hh
  • int main()
  • Arrayltintgt a(10)
  • try
  • a3 3
  • a10 5 // oops!
  • catch (stdstring s)
  • stdcout ltlt s ltlt stdendl
  • return 0

9
Templates issues
  • All the Array code is in the header file!
  • Template is like a big macro that gets expanded
    to a real type when given a type argument
  • In theory, can define template member functions
    in a separate class and compile separately in
    practice, few compilers support this (g doesnt)

10
Templates wrapup
  • Much, much more to templates!
  • Whole books have been written on templates
  • Can write templated functions
  • Can use integer template parameters
  • Default template parameters
  • Multiple template parameters
  • STL (Standard Template Library)
  • See the advanced C track for more
Write a Comment
User Comments (0)
About PowerShow.com