Re: "comparable" interface for generic/templated objects?
On Feb 8, 1:33 am, vk <vmi...@gmail.com> wrote:
short question:
If I have a class with 1 generic type (type T), what is the
best way to compare objects of type T?
bkgd:
We wrote this generic java priority queue which uses a
min-heap (stored in an ArrayList) for class. All of the
objects in the min-heap are of a single (unknown at compile
time) type. This unknown type has to implement
java.lang.Comparable so in the priority queue, I can decide
which node to put where. The function to compare objects just
casts them to the Comparable interface and then calls the
obj.compareTo (obj) method.
I'm looking to improve my c++, so I decided to re-write it (in
c++). If there is a Comparable (or similar) interface that
works with primitives and objects, it would be good to know.
Since the other programmers seem to be more interested in
arguing with one another than with answering your question:-):
C++ supports two types of genericity. Most of the time, objects
in containers have value semantics, and are not (run-time)
polymorphic; if you possibly can, that's what you should do as
well. In this case, the "polymorphism" is resolved at compile
time, and uses duck typing---you don't have to derive from any
given interface, just provide the required functionality. (In
this case, by default, an operator<, or more precisely,
std::less, which by default uses operator<.)
If you need a container which contains several different types
(all deriving from a common base), you need a container of
pointers, since containers do not support polymorphic objects.
This introduces several additional complexities, like managing
the memory. And In this case, you'll have to specify the
comparison function anytime it is needed (since comparison of
pointers only takes into account the pointer value, and defines
an arbitrary ordering). If you need to do this, you can define
your own Comparable interface, and derive from it. You then
define the comparator type you use for the functions to call it.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34