Boost logo

Boost :

From: Vincent Poinot (vincent.poinot_at_[hidden])
Date: 2007-06-20 14:16:43


I recently developped some small utility classes and I wonder if this could
be interesting for other people.

The motivation is the following: when manipulating containers of pointers,
standard algorithms won't work out of the box, e.g. if I want to sort a
vector of pointers to a class X, I have to pass to sort() a new comparison
function object that will dereference its arguments so that the proper
operator< may be called on the values.

So I wrote a piece of code that creates this new "dereferencing" function
object automatically. Here is what it looks like, assuming a class X with a
properly defined operator<(const X&, const X&)

int main()
    vector<X*> v ;

    // Populate v here

    // Testing dereferencing of binary function object
    sort(v.begin(), v.end(), deref<X*>(less<X>())) ;

As you can see, the available comparison function objects operates on
objects X, the deref() helper function creates a new function object that
will call the original less<>() after dereferencing its arguments, allowing
sort() to work as expected.

Two other examples (assuming there is also an operator+ and an operator==
for X objects):

X sum = accumulate(v.begin(), v.end(), X(), deref<X*>(plus<X>())) ;
remove_if(v.begin(), v.end(),
          deref<X*>(bind2nd(equal_to<X>(), X(something)))) ;

I am well aware that lambda functions can solve this problem much more
elegantly, but the reason why I wrote this is that I cannot use Boost at
work :-( And now that it is written, well, maybe somebody else can find
this useful...

(This stuff also works with smart pointers.)

Vincent Poinot.

Boost list run by bdawes at, gregod at, cpdaniel at, john at