This is more of a code clenliness question, cause I already have an example here. I'm doing this a ton in code and the creation of all these lambdas (some of which are the same) has begun to irk me.
So given the struct:
struct foo {
int b() const { return _b; }
int a() const { return _a; }
int r() const { return _r; }
const int _b;
const int _a;
const int _r;
};
I have a container of pointers to them, let's say vector<foo*> foos
, now I want to go through the container and get the sum of one of the fields.
As an example if I wanted the field _r
, then my current approach is to do this:
accumulate(cbegin(foos), cend(foos), 0, [](const auto init, const auto i) { return init + i->r(); } )
I'm writing this line everywhere. Can any improvement be made upon this? I'd really like to write something like this:
x(cbegin(foos), cend(foos), mem_fn(&foo::r));
I don't think the standard provides anything like that. I could obviously write it, but then it would require the reader to go figure out my suspect code instead of just knowing what accumulate
does.