Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

16.2 Building on the Standard Containers

Let's examine a few of the ways you can use existing C++ Standard Library containers to create your own containers. For example, say you want to implement a set container that enforces unique values that are not inherently sorted. You also want a group of algorithms to operate on that set. The container is certainly a sequence but not an associative container, since an associative container is sorted by definition. The algorithms will presumably work on other sequences, assuming those sequences provide appropriate iterator types, since the iterator required by a set of algorithms determines the range of containers those algorithms can be applied to. The algorithms will be universally available if they require only forward iterators. On the other hand, they'll be most restrictive if they require random access iterators.

Simple implementations of this set container could make use of existing C++ Standard Library containers for much of their mechanics. Three possible ways of achieving this code reuse are:

Let's take a look at each of these approaches in the next sections.

16.2.1 Inheritance

As you recall, inheritance is the powerful feature of object-oriented programming that allows objects to derive attributes and behavior from other objects. To create your own container, you could derive from an existing Standard C++ container, then override certain functions to get the desired behavior. One approach would be to derive from the vector container, as shown here:

16.2.2 Generic Inheritance

A second approach to creating your own container is to create a generic adaptor, rather than specifying vector. You do this by providing the underlying container through a template parameter:

If you use generic inheritance through an adaptor, the adaptor and users of the adaptor cannot expect more than default capabilities and behavior from any container used to instantiate it. If the adaptor or its users expect functionality beyond what is required of a basic container, the documentation must specify precisely what is expected.

16.2.3 Generic Composition

The third approach to building your own container uses composition rather than inheritance. You can see the spirit of this approach in the C++ Standard Library adaptors queue, priority queue, and stack. When you use generic composition, you have to implement all of the desired interface. This option is most useful when you want to limit the behavior of an adaptor by providing only a subset of the interface provided by the container.

The advantages of adapting existing containers are numerous. For instance, you get to reuse the implementation and the specifications of the container that you're adapting.



Previous fileTop of DocumentContentsIndex pageNext file