Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
Sorting letters
Remember I did two colums on counted pointers?
Well.
You might want to add another little template class that let's you sort the handle based on the inside body class.
Here's how.
Introduction
I left you in lost+found 12 with a CountedPointer template. We can adjust this template by adding some stuff and end up with a SortableCountedPointer. We don't need much, just add an equality operator and a less-than operator:
templateclass SortableCountedPointer : public CountedPointer { public: SortableCountedPointer(T* objptr = 0) : CountedPointer(objptr) {} CountedPointer (const CountedPointer & that) : CountedPointer(that) {} CountedPointer & operator=(const CountedPointer & that) { if (this != &that) { CountedPointer ::operator=(that); } return *this; } ~ CountedPointer () {} bool operator==(const SortableCountedPointer & that) const { return (**this == *that); } bool operator<(const sortablecountedpointer & that) const { return (**this < *that); } };
More handle magic
Now, you will say, what is this business with the double dereference of this in the comparison operators? Can you remember the base class CountedPointer? It included operator* that returned a reference to the inner class right? Ok. What happens is that this is a const pointer to the object. Dereferencing it once will yield a reference to the object itself. Dereferencing the second time will call operator*() and will return a reference to the inner class. Then we invoke operator== of the inner class. Bingo. We are comparing the inner object. For 'that' it is the same story. 'that' is a reference to the other handle object. Calling operator* on it will yield a reference to the inner object, and that is exactly what we want as the parameter for the equality operator of the inner object.
Inner object requirements
If you want to apply this kind of trick, we need two operators in the inner object. These are:
bool InnerObject::operator==(const InnerOjbject& that) const; bool InnerObject::operator<(const innerojbject& that) const;That's all.