Book Image

Microsoft Visual C++ Windows Applications by Example

By : Stefan Bjornander, Stefan Björnander
Book Image

Microsoft Visual C++ Windows Applications by Example

By: Stefan Bjornander, Stefan Björnander

Overview of this book

Table of Contents (15 chapters)
Microsoft Visual C++ Windows Applications by Example
Credits
About the Author
About the Reviewer
Preface
Index

Templates


Suppose that we need a stack of integers in an application. We could use the one in the previous section. Then maybe we also need a stack of characters, and maybe another one of car objects. It would certainly be a waste of time to repeat the coding for each type of stack. Instead, we can write a template class with generic types. When we create an object of the class, we specify the type of the stack. The condition is that the methods, functions, and operators used are defined on the involved types; otherwise, a linking error will occur. Due to linking issues, both the definition of the class and the methods shall be included in the header file. The following is a template version of the stack.

TemplateCell.h

template <typename Type>
class Cell
{
  public:
    Cell(Type value, Cell<Type>* pNextCell);

    Type& Value() {return m_value;}
    const Type Value() const {return m_value;}
    Cell<Type>*& Next() {return m_pNextCell;}
    const Cell<Type&gt...