Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2004-03-03 18:11:06


"Powell, Gary" <powellg_at_[hidden]> writes:

>> 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,

It can return a proxy whose operator->() returns a proxy whose
operator->() ... returns a pointer.

> in this case to an object which has
> a member fn "at".

Right; what's the problem?

> 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.

I'm not doing vector<X>::at; please re-read the example. Pick another
name, say "member":

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

We could think of other syntaxes, probably.

> 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.

Sure. But in the meantime I'd like a slightly sweeter syntax for
member access.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

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