map and virtual operator< for base class

John S. Fine johnsfine@verizon.net
Tue May 11 12:33:00 GMT 2010


Can you implement a comparison operator that compares the multiple class 
types to each other?

If not, they can't be in the same map.  You must be able to compare any 
object you will put in the map to any object already in the map.

If you can compare them, I wouldn't expect the easiest implementation to 
involve a virtual operator<(), but if it does involve a virtual 
operator<(), that isn't a fundamental problem.  There are ways around 
the masking issue I posted about earlier.

I think the more fundamental problem is storing polymorphic objects in a 
container.

I don't use boost much, and I have no idea what support boost might 
provide for polymorphic objects in a container.

In my own programming that is a common requirement and I have 
implemented the underlying support in at least two different ways.

1) With pointer semantics, rather than value semantics, on all objects 
retrieved from the container.  For that it is easiest to use a wrapper 
class around the pointer that forwards operator<() to the object pointed 
at.  Then have a container of those pointers.  When setting that up, 
there are several choices possible for who owns the objects, whether the 
objects are cloned when inserted into the container, whether the 
destruction of the pointer wrapper destroys the object, etc.  Depending 
on use, there is no one correct combination of those choices, but there 
are many incorrect combinations.  Think through the ownership, copy and 
deletion issues carefully.

2) With value semantics.  I've never covered every detail to make this a 
clean generic container.  I've just made it good enough for my own use.  
The container holds pointers, rather than objects.  But the operator[]() 
on the container and the behavior of the iterator objects returned by 
many other functions of the container all pretend the container holds 
objects (by adding the extra level of dereference).  Again there are 
lots of choices (which I did as template parameters) for whether you 
clone on insertion and whether you delete on removal, whether you count 
ownership, or assume single ownership or assume external ownership.

C++ obviously has no standard support for clone.  Simple copying of a 
polymorphic object copies only the base class, which is the most 
fundamental problem in a container of polymorphic objects.  I prefer to 
simply implement the clone() function in any class hierarchy that has 
use for it.  So if one of my containers needs clone() it just calls 
clone().  If the object has no clone method, that was a mistake in the 
choice to use that type of container for that type of object.

Bernd Prager wrote: 
>
> So the only way basically is then to have a separate map for each 
> class, right?
> Is there a better way to implement a class cache for multiple class 
> types?
>
>



More information about the Gcc-help mailing list