|
Boost Users : |
From: Jaakko Jarvi (jajarvi_at_[hidden])
Date: 2003-06-24 14:35:17
> Hi!
> I would like to write code like
> int main()
> {
> namespace l = boost::lambda;
> std::map<int, double> M;
> M[1] = 5.0;
> M[3] = 7.0;
> std::for_each(M.begin(), M.end(),
> l::select2nd(l::_1) *= 6.0);
> }
> Is it hard to implement this for boost::lambda?
> Markus
Accessing data members can be done, but it's unfortunately a bit more
complicated than:
_1.second
I just wish . could be overloaded.
Example code below.
Cheers, Jaakko
--------------------
#include "boost/lambda/lambda.hpp"
#include "boost/lambda/bind.hpp"
#include <algorithm>
#include <map>
#include <iostream>
// A function object class that takes returns a second argument of a pair.
// This can be used with bind.
struct select2nd {
// Tell LL how to get the return type. Args will be tuple<select2nd, pair<int, double> >,
// so get the element at index 1.
template <class Args>
struct sig {
typedef typename
boost::tuples::element<1, Args>::type pair_t;
typedef typename boost::add_reference<typename pair_t::second_type>::type type;
};
template <class T>
typename boost::add_reference<typename T::second_type>::type
operator()(T& t) const { return t.second; }
};
int main()
{
namespace l = boost::lambda;
std::map<int, double> M;
M[1] = 5.0;
M[3] = 7.0;
std::for_each(M.begin(), M.end(), std::cout << l::bind(select2nd(), l::_1) << " ");
std::cout << std::endl;
std::for_each(M.begin(), M.end(), l::bind(select2nd(), l::_1) *= 6.0);
std::for_each(M.begin(), M.end(), std::cout << l::bind(select2nd(), l::_1) << " ");
std::cout << std::endl;
// alternatively, use bind to refer directly to the data member. You need to
// spell out the full type of the pair though.
std::for_each(M.begin(), M.end(),
l::bind(&std::map<int, double>::value_type::second, l::_1) *= 6.0);
std::for_each(M.begin(), M.end(), std::cout << l::bind(select2nd(), l::_1) << " ");
std::cout << std::endl;
}
-------------------
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net