Department of Computer and Information Science, School of Science, IUPUI - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

Department of Computer and Information Science, School of Science, IUPUI

Description:

Two Types -- Function and Class Templates. 12/24/09. 3. Dale Roberts. Function ... Compiler Creates Appropriate Function Definition Using the Argument Specified ... – PowerPoint PPT presentation

Number of Views:42
Avg rating:3.0/5.0
Slides: 8
Provided by: dalero
Learn more at: http://cs.iupui.edu
Category:

less

Transcript and Presenter's Notes

Title: Department of Computer and Information Science, School of Science, IUPUI


1
Department of Computer and Information
Science,School of Science, IUPUI
Templates
  • Dale Roberts, Lecturer
  • Computer Science, IUPUI
  • E-mail droberts_at_cs.iupui.edu

2
Templates
  • A Template Defines the Content of a Family of
    Data Types
  • Two Types -- Function and Class Templates

3
Function Templates
  • Specifies a Generic Class and Uses this Class in
    the Function Algorithm
  • Compiler Creates Appropriate Function Definition
    Using the Argument Specified During a Function
    Call Invocation

4
Function Template -- Example
  • includeltstream.hgt
  • //Template Function Definition
  • template ltclass Tgt T maximum(T t1, T t2)
  • if (t1 gt t2) return t1
  • else return t2
  • main()
  • int a 10, b 15
  • float c 20.0, d 25.5
  • cout ltlt "Maximum Integer " ltlt maximum(a, b)
    ltlt endl
  • cout ltlt "Maximum Float " ltlt maximum(c, d) ltlt
    endl
  • //ERROR....Parameter Type Mismatch -- No
    Conversion
  • cout ltlt "Maximum " ltlt maximum(a, d) ltlt endl
  • //Explicit Prototype for Forced Conversion
  • float maximum(float, float)

5
Class Template
  • Specifies a Generic Class and Uses it in the
    Algorithm
  • Proper Arguments Must be Supplied Before Creating
    an Instance (or Object) Using the Template Class

6
Class Template -- Stack Example
  • //A Stack of Arbitrary Elements
  • template ltclass Tgt class stack
  • T head
  • T tail
  • int sz
  • public
  • stack(int s)head tail new Tsz s
  • stack()delete head
  • void push(T a) tail a
  • T pop() return --tail
  • int size() const return tail - head
  • main()
  • //Stack of 100 Characters
  • stackltchargt char_stack(100)
  • char_stack.push('R')
  • cout ltlt "Stack Size " ltlt char_stack.size()
    ltlt endl

7
Class Template -- Stack Example -- Cont'd
  • OUTPUT WILL BE
  • ------ ---- --
  • Stack Size 1
  • Top 10
Write a Comment
User Comments (0)
About PowerShow.com