Building on the standard containers, Inheritance, Generic inheritance – HP Integrity NonStop H-Series User Manual

Page 209

Advertising
background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Building on the Standard Containers

Let's examine a few of the ways you can use existing Standard C++ 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, by definition, sorted. 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 only require 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 existing Standard Library containers for much of their
mechanics. Three possible ways of achieving this code re-use are:

Inheritance;

Generic inheritance;

Generic composition.

Let's take a look at each of these approaches.

Inheritance

The new container could derive from an existing standard container, then override certain functions to get the desired
behavior. One approach would be to derive from the

vector

container, as shown here:

#include <vector>

// note the use of a namespace to avoid conflicts with standard // or global names

namespace my_namespace {

template <class T, class Allocator = std::allocator>
class set : public std::vector<T,Allocator>
{
public:
// override functions such as insert
iterator insert (iterator position, const T& x)
{
if (find(begin(),end(),x) == end())
return vector<T,Allocator>::insert(position,x);
else
return end(); // This value already present!
}
_

};

} // End of my_namespace

Advertising
This manual is related to the following products: