beautypg.com

Generic composition, Generic inheritance – HP Integrity NonStop H-Series User Manual

Page 210

background image

Generic Inheritance

A second approach is to create a generic adaptor, rather than specifying

vector

. You do this by providing the underlying

container through a template parameter:

namespace my_namespace {

template >
class set : public Container
{
public:
// Provide typedefs (iterator only for illustration)
typedef typename Container::iterator iterator;

// override functions such as insert
iterator insert (iterator position, const T& x)
{
if (find(begin(),end(),x) == end())
return Container::insert(position,x);
else
return end(); // This value already present!
}
_

};

} // End of my_namespace

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.

Generic Composition

The third approach uses composition rather than inheritance. (You can see the spirit of this approach in the Standard
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.

namespace my_namespace {

template >
class set
{
protected:
Container c;
public:
// Provide needed typedefs
typedef typename Container::iterator iterator;

// provide all necessary functions such as insert
iterator insert (iterator position, const T& x)
{
if (find(c.begin(),c.end(),x) == c.end())
return c.insert(position,x);
else
return c.end(); // This value already present!
}

This manual is related to the following products: