Lecture-18-Templates

Lecture-18-Templates - C Templates Templates The...

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

View Full Document Right Arrow Icon
C++ Templates
Background image of page 1

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

View Full DocumentRight Arrow Icon
Templates ± The StringStack class only knows how to store strings ± What if we need stacks of ints, floats, Elephants, … ± We could write stack classes for each different type ± Results in lots of classes and maintenance effort ± C++ has a feature called "templates" that allows us to write a class blueprint, and then create lots of real classes based on that blueprint ± Different terms for the same idea: ± Templates ± Generic types (or just “generics”) ± Parameterized types
Background image of page 2
Templates template <typename T> class Stack { }; Stack<string> strStack(5); strStack.Push("one"); cout << strStack.Pop() << endl; Stack<int> intStack(5); intStack.Push(1); cout << intStack.Pop() << endl; Stack<Elephant> eleStack(5); eleStack.Push(Elephant(6000)); cout << eleStack.Pop() << endl;
Background image of page 3

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

View Full DocumentRight Arrow Icon
Converting StringStack Into a Stack Template ± Add the line "template <typename T>" before the class declaration ± Change the name of the class to Stack ± Everywhere in the code that we used the type
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.

Page1 / 13

Lecture-18-Templates - C Templates Templates The...

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