|
Boost : |
From: David Abrahams (dave_at_[hidden])
Date: 2004-03-03 15:31:21
I just tried using the lambda library for the first time. Here's
what came out of it, after some struggle:
#include <boost/lambda/lambda.hpp>
#include <vector>
#include <numeric>
using namespace boost::lambda;
struct X
{
X() : count(1) {}
unsigned long count;
};
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 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