2009/3/3 Igor R
<boost.lists@gmail.com>
Hello,
I'd like to bind std::for_each with some other functor created on the
fly, like this:
struct A
{
void f(int, int);
};
vector<shared_ptr<A> > vec;
void f(function<void(void)>);
// I want to call f() with a functor that would call A::f for every
element in vec
f(bind(&for_each, vec.begin(), vec.end(), bind(&A::f, _1, 1))); //
doesn't compile
f(bind(&for_each, vec.begin(), vec.end(), protect(bind(&A::f, _1,
1)))); // also doesn't compile
That's what lambda algorithms are for.
#include <vector>
#include <boost/lambda/algorithm.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
struct A {
void f() {}
};
int main() {
using namespace boost::lambda;
std::vector<A> v;
bind(ll::for_each(), v.begin(), v.end(), protect(bind(&A::f, _1)))();
}
Unfortunately, lambda::bind does not play well with smart pointers. You can add one more bind to that expression to extract pointer from shared_ptr or you can use boost::bind instead of lambda::bind.
#include <vector>
#include <boost/bind.hpp>
#include <boost/bind/protect.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/lambda/algorithm.hpp>
int main() {
std::vector<boost::shared_ptr<A> > v;
boost::bind<void>(boost::lambda::ll::for_each(),
v.begin(),
v.end(),
boost::protect(boost::bind(&A::f, _1)))();
}
Roman Perepelitsa.