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); ...
Get C++ Templates: The Complete Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.