Re: pointer problem

From: Thomas Baier (thomas_at_tho-bai.de)
Date: 11/03/03


Date: Mon, 03 Nov 2003 22:30:54 +0100

Works fine, but is there a way to overload the <-operator so that
a<b is the same as &a<&b?

Rob Williscroft wrote:

> Thomas Baier wrote in
> news:3fa6bf6a$0$3453$9b4e6d93@newsread4.arcor-online.net:
>
>> Hi there,
>>
>> I've written a list template class and a tree template class. The list
>> class contains some sort algorithms and I have to sort a list with
>> elements of type tree<T>*. So I need to compare these elements. I've
>> overloaded the <,>,<=,>= operators of the tree class, but of course
>> that doesn't work cause I don't have to compare elements of type
>> tree<T>, but elements of type tree<T>*. So if I would make
>>
>> tree<int> a(3);
>> tree<int> b(4);
>> cout << a<b;
>> everything works fine. But I have to do something like
>>
>> tree<int>* a = new tree<int>(3);
>> tree<int>* a = new tree<int>(4);
>> cout << a<b;
>>
>> I know that this would just compare the adresses of both objects, but
>> I don't know how to solve that, cause at running time "I" do not know
>> whether the elements of my list are pointers or not. So I cannot write
>> *a<*b
>> cause it could be that a and b aren't pointers.
>>
>> Is there any way to solve that problem (a way to find out whether
>> there were pointers or not or something like that)
>>
>>
>
> #include <iostream>
> #include <iomanip>
>
> template < typename T >
> struct less_helper
> {
> static bool apply( T const &lhs, T const & rhs )
> {
> return lhs < rhs;
> }
> };
>
> // Now specialize for pointer:
>
> template < typename T >
> struct less_helper< T * >
> {
> static bool apply( T const *lhs, T const *rhs )
> {
> return *lhs < *rhs;
> }
> };
>
> //use:
>
> template < typename T >
> bool example_is_less( T const &lhs, T const &rhs )
> {
> return less_helper< T >::apply( lhs, rhs );
> }
>
> int main()
> {
> using namespace std;
>
> int a = 1, b = 2;
>
> cerr << boolalpha;
>
> cerr << example_is_less( a, b ) << "\n";
> cerr << example_is_less( a, a ) << "\n";
> cerr << example_is_less( b, a ) << "\n";
>
> cerr << example_is_less( &a, &b ) << "\n";
> cerr << example_is_less( &a, &a ) << "\n";
> cerr << example_is_less( &b, &a ) << "\n";
>
> // check it isn't address dependant:
> b = 1, a = 2;
>
> cerr << example_is_less( &b, &a ) << "\n";
> cerr << example_is_less( &b, &b ) << "\n";
> cerr << example_is_less( &a, &b ) << "\n";
> }
>
> HTH
>
> Rob.