Boost logo

Boost :

From: Powell, Gary (powellg_at_[hidden])
Date: 2004-03-03 16:34:50


> std::vector<X> xs(10);
> unsigned long n = std::accumulate(
> xs.begin(), xs.end(), 0UL,
> _1 + (&_2) ->* &X::count);

>This program adds up the "count" members in a vector of X objects.
>Now, no offense intended, but this is nasty. There's just too much
>extra syntax required for something so simple, plus you have to make
>the type into a pointer just so you can dereference it Before I
>realized I needed to take the address of _2, I had:

> unsigned long n = std::accumulate(
> xs.begin(), xs.end(), 0UL,
> _1 + _2 ->* &X::count);

>which is only slightly better (but incorrect). I realize that I can
>use bind:

    
> unsigned long n = std::accumulate(
> xs.begin(), xs.end(), 0UL,
> _1 + bind(&X::count,_2));

>but that's slightly counter-intuitive since the order of the target
>object and its member pointer are reversed. It'd be nice to allow
>something like:

> unsigned long n = std::accumulate(
> xs.begin(), xs.end(), 0UL,
> _1 + _2.at(&X::count));

>while if _2 were to refer to a pointer type, we could say:

> unsigned long n = std::accumulate(
> xs.begin(), xs.end(), 0UL,
> _1 + _2->at(&X::count));
 
>Dave Abrahams

I tried to overload operator->() for a lambda object, but the C++ rule is that it _Must_ return a pointer, in this case to an object which has a member fn "at". So you are toast, because I couldn't figure out how to hold a pointer to a lambda object and recognize it as a delayed object holding a member pointer to vector<X>::at. When we aren't given the information about the member pointer.

I'm working on a paper to allow us to overload operator.(), but the last time it was discussed in committee it burned the hair off of nearby dogs and scared children. So I'm waiting until the Redmond meeting so I won't have far to drag my burnt carcass home.

Meantime it again highlights that a core language change to allow anonymous fns is needed so this whole mechanism of BLL can go away.

// PROPOSED CHANGE IN SOME FUTURE PAPER

unsigned long n = std::accumulate(
      xs.begin(), xs.end(), 0UL,
          long (long lhs, X const &rhs) // inline fn with no name.
          {
              return lhs + rhs.count;
          }
      );

  Yours,
  -Gary-


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