|
Boost : |
From: Thorsten Ottosen (nesotto_at_[hidden])
Date: 2003-10-11 23:48:53
Alex writes:
>
> "Thorsten Ottosen" <nesotto_at_[hidden]> wrote in message
[snip]
> > struct ptr_less_than
> > {
> > template< typename T >
> > bool operator()( const T*l, const T* r)
> > {
> > *l < *r;
> > }
> > };
> >
> > sort( v.ptr_begin(), v.ptr_end(), ptr_less_than() );
>
> Thorsten,
> One disadvantage of this approach is that it requires you to define
> specialized function objects which act on pointers. If your operator*()
> returns some sort of proxy, as you originally suggested, you can provide
it
> with an implicit cast to const T &. This will allow you to sort the
> ptr_vector without defining ptr_less_than. You can simply use
std::less<T>.
>
> sort(v.ptr_begin(), v.ptr_end(), std::less<T>());
that's one possibility and I like it. I was settling for something like in
this example:
template< typename Pred >
class indirected_predicate
{
Pred pred_;
public:
indirected_predicate( Pred p ) : pred_( p )
{ }
template< typename T >
bool operator()( T* t ) const
{
return pred_( *t );
}
template< typename T >
bool operator()( T* l, T* r ) const
{
return pred_( *l, *r );
}
};
template< typename Pred >
inline indirected_predicate<Pred> indirected( Pred p )
{
return indirected_predicate<Pred>( p );
}
using namespace std;
int main()
{
vector<int*> v;
sort( v.begin(), v.end(), indirected( less<int>() ) );
}
My biggest headache is to get the proxy to make the assignments properly in
the proxy. I'm get memory curruption
with what I currently have:
template< typename ValueType, typename PtrIterator >
class iterator_proxy
{
typedef BOOST_DEDUCED_TYPENAME ::boost::remove_pointer<ValueType>::type T;
typedef iterator_proxy<ValueType,PtrIterator> this_type;
PtrIterator& i_;
void shallow_copy( PtrIterator to, PtrIterator from )
{
*to = *from;
}
public:
explicit iterator_proxy( PtrIterator& i ) : i_( i )
{
}
iterator_proxy( const iterator_proxy& r ) : i_( r.i_ )
{
}
// I supect this one to be wrong
iterator_proxy& operator=( const iterator_proxy& r )
{
shallow_copy( i_, r.i_ );
i_ = r.i_;
return *this;
}
bool operator==( const this_type& r ) const
{
return **i_ == **r.i_;
}
bool operator<( const this_type& r ) const
{
return **i_ < **r.i_;
}
};
Since I couldn't get this right I stated looking for alternatives.
cheers
Thorsten
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk