Boost logo

Boost :

From: Andy Sawyer (boost_at_[hidden])
Date: 2003-07-12 07:21:49


Edward Diener writes:
> Andy Sawyer wrote:
>
> > Marshall's "first" and "second" are slightly different to the HP
> > versions:
> >
> > template <class T1, class T2>
> > struct first: std::unary_function< std::pair <T1, T2>, T1>
> > ...
> >
> > vs.
> >
> > template<typename Pair>
> > struct select1st
> > : std::unary_function< Pair, typename Pair::first_type>
>
> Yes, I see it now. Marshall's version seems a little more redundant since
> one has to specify both types while the HP version just has one specifying a
> single pair type.

This is particularly useful when you're dealing with std::map:

map_t some_map;
...
for_each( some_map.begin(), some_map.end(),
          select2nd<some_map::value_type>() );

Since you normally have the "pair type" trivially available at the call
site. (Of course, you also have the first_type and second_type available).

There's a third form I've also found useful on occasion:

struct selector1st
{
  template<typename Pair>
  const typename Pair::first_type& operator()( const Pair& a ) const
  {
    return a.first;
  }
};

(selector2nd is left as an excercise for the reader :)

Which has the advantage of not needing to specify _any_ type at the call
site:

for_each( map.begin(), map.end(), selector1st() );

And again, is not limited to use with std::pair. However, it's utility
is limited by not inheriting from std::unary_function.

> >
> > I think these disappeared from the standard around the same time as
> > project1st/project2nd? (or at least, didn't make it in at around the
> > same time :)
>
> Yes, Austern's book also mentions project1st and project2nd.

Indeed it does (I checked shortly after my last post :)

> I believe one can build an even more flexible function object which
> returns an object of any type among multiple types using the Boost
> Tuple implementation. Of course one would have to pass an index to
> such a function object, which makes it a little more complicated to
> use than the pair implementations being discussed. Or one could have
> tuple_select1st... through tuple_selectxxx function objects up to
> some arbitrary limit. Maybe Jaakko Jarvi can add such a function
> object to the Tuple library if others find it useful.

It would certainly be a useful addition (IMO, at least), although I
think many users would be happy with a version that works for std::pair
(the common case, of course, being operations on the elements of std::map)

Regards,
 Andy S.

-- 
"Light thinks it travels faster than anything but it is wrong. No matter
 how fast light travels it finds the darkness has always got there first,
 and is waiting for it."                  -- Terry Pratchett, Reaper Man

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk