supp-template

supp-template - CSC 1111 Introduction to Computing using C...

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

View Full Document Right Arrow Icon
1 CSC 1111 Introduction to Computing using C++ Function and Class Templates and Standard Template Library (STL)
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 Function Templates Mechanism for parameterizing a function with a type e.g.: template <class T> void printWithBox( T value) { cout << '[' << value << ']'; } Define a generic function that can be applied to any type of data. T , an identifier representing a type which serves as a parameter to the template function. Compilers automatically create different copies of the functions on demand base on the type of the argument.
Background image of page 2
3 #include <iostream> #include <sstream> #include <string> using namespace std; template <class T> string toString( T t) { ostringstream sout; sout << t; return sout.str(); } int main() { string s1 = toString (-11); string s2 = toString (true); string s3 = toString (123.45); cout << s1 << endl; cout << s2 << endl; cout << s3 << endl; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 string toString ( int t) { ostringstream sout; sout << t; return sout.str(); } string toString ( bool t) { ostringstream sout; sout << t; return sout.str(); } string toString ( double t) { ostringstream sout; sout << t; return sout.str(); } Based on the type of the arguments in the function call, compilers automatically create the appropriate function out of the template function.
Background image of page 3

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

View Full DocumentRight Arrow Icon
4 template <class T> void selectionSort( T num[], int n) { for ( int i = 0; i < n - 1; i++ ) {
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

Page1 / 13

supp-template - CSC 1111 Introduction to Computing using C...

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

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