O'Reilly logo

C++ Templates: The Complete Guide, 2nd Edition by Douglas Gregor, Nicolai M. Josuttis, David Vandevoorde

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2

Class Templates

Similar to functions, classes can also be parameterized with one or more types. Container classes, which are used to manage elements of a certain type, are a typical example of this feature. By using class templates, you can implement such container classes while the element type is still open. In this chapter we use a stack as an example of a class template.

2.1 Implementation of Class Template Stack

As we did with function templates, we declare and define class Stack<> in a header file as follows:

basics/stack1.hpp

#include <vector> #include <cassert> template<typename T> class Stack {      private:      std::vector<T> elems;      // elements    public:      void push(T const& elem);   ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required