Boost logo

Boost Users :

Subject: Re: [Boost-users] boost lambda and bind
From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2009-12-18 05:33:02


On Fri, Dec 18, 2009 at 9:36 AM, Conoscenza Silente
<abruzzoforteegentile_at_[hidden]> wrote:
>
> Hi All
> I am trying to use boost lambda for looping over a std::map to get each element and
> pass those to a class function using lambda functions.
> I don't know why but the binding inside my std::for_each is not compiling and I have 2 errors
> pointing to the line where boost::assign is used.
>
> 'invalid initialization of reference of type int&'
> 'invalid initialization of reference of type std::basic_string<>&'
>
> Do you know how to fix this and why it is happening
> Thank you very much
> Regards
> CS
>
> //Boost
> //#include<boost/assign/std/map.hpp>
> #include<boost/assign/list_of.hpp>
>
> #include<boost/lambda/lambda.hpp>
> #include<boost/lambda/core.hpp>
> #include<boost/lambda/bind.hpp>
> #include<boost/lambda/construct.hpp>
>
>
>
> class CInnerClassHandler{
>     public:
>         void DoSomething( int aIntValue, const std::string& aStringValue ){
>
>             std::cout   << "INT:" << aIntValue
>                         << "STRING:" << aStringValue
>                         << std::endl; // here we just trace
>         }
>     };
>
> void map_lambda_test(){
>
>         typedef std::pair< int, std::string > this_pair;
>
>         std::map< int, std::string > dictionary =
>             boost::assign::map_list_of(3,"A")(4,"B")(5,"C");  // Errors points to
>         // this line of code
>
>         CInnerClassHandler obj;
>
>         std::for_each(
>             dictionary.begin(),
>             dictionary.end(),
>                 boost::lambda::bind(
>                     &CInnerClassHandler::DoSomething, &obj,
>                           boost::lambda::bind(&this_pair::first, boost::lambda::_1),
>                           boost::lambda::bind(&this_pair::second,boost::lambda::_1))
>             );
>     }
>

The errors are because this_pair doesn't accurately define the pair
passed to the lambda function - maps actually use a pair with a const
key. Try using this typedef for this_pair instead:

        typedef std::map< int, std::string >::value_type this_pair;

HTH

Stuart Dootson


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