Templates - Lecture 8: Templates CS256 Fall 2008 Outline...

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

View Full Document Right Arrow Icon
Lecture 8: Templates CS256 – Fall 2008
Background image of page 1

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

View Full DocumentRight Arrow Icon
Outline Template functions Templates and Function overloading Template classes Case studies List Matrix
Background image of page 2
Why Template Functions Try to define a function that works with many different types of values Example: void print (ostream& out, int data[], int size); This print function only works for an array of int Need an overloading function for an array of double void print (ostream& out, double data[], int size); The only difference between these functions is the argument type. Can we reuse it without rewriting?
Background image of page 3

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

View Full DocumentRight Arrow Icon
Template Functions A template allows a function or a class definition to be parameterized by types Work with many different types of values. Example template<typename T> for (int j=0; j<size; j++) out << data[j] << “ “; out << endl; }
Background image of page 4
Example – Swap_values template <typename T> T temp; temp = a; a=b; b=temp; return; } int v1=5, v2=7; swap(v1,v2); double d1, d2; …; swap(d1,d2); Note: The above codes work under g++ but may not work under Visual C++
Background image of page 5

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

View Full DocumentRight Arrow Icon
Formal Definition Purpose Define a function that can be reused for different types of arguments Syntax template<typename type_variable1, …, typename type_variable2> return_type function_name(parameters) { statements } within the function body, type_variables can be used whenever a type would be appropriate
Background image of page 6
Old Fashioned Syntax Instead of using the keyword typename, the
Background image of page 7

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

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

Page1 / 21

Templates - Lecture 8: Templates CS256 Fall 2008 Outline...

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

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