
On Tue, Jan 20, 2009 at 2:21 PM, Alan M. Carroll < amc@network-geographics.com> wrote:
Why not use Boost.Bind? It will bind to data members, returning a functor that accesses that member. E.g.
boost::bind(&A::a, _1);
will create a functor that takes an instance of A and returns a reference to the a member. You can then pass that to whatever other functor is being used. Something like (not tested!)
std::accumulate(m.begin(), m.end(), bind(std::add, _1, bind(&std::map<std::string, int>::value_type::first, _1));
Boost.Lambda can do this as well, but I am not familiar enough with it to provide an example.
The Lambda version would be similar, just replacing the outer bind with infix notation #include "boost/lambda/lambda.hpp" #include "boost/lambda/bind.hpp" using namespace boost::lambda; std::accumulate( begin, end, _1 + bind(&A::a, _2 )); Again untested.
At 07:22 AM 1/20/2009, you wrote:
Hi again,
I have a problem. Not really big one but annoying. Often we need to write code like this:
struct A{ int a; std::string b; };
int a_sum(int i, const A &v){ return v.a + i; };
std::vector<A> v; //fill this vector somewhere
std::accumulate( v.begin(), v.end(), 0, a_sum );
or something like
int m_sum(int i, const std::pair<int, std::string> p) { return p.first + i; };
std::map <std::string, int> m;
std::accumlate( m.begin(), m.end(), 0, m_sum);
Or in common words we need to write some kind functor which just get member from element and apply it to another functor.
Of course I can write something like:
template<typename T_, typename V_, V_ T_::*Ptr_> struct get_mem{ const V_ &operator()(const T_ &elem){ return elem->*Ptr_; }; };
but may be there is library way to do this?