Boost logo

Boost Users :

Subject: Re: [Boost-users] naming delayed variables string in boost lamdba
From: Roman Perepelitsa (roman.perepelitsa_at_[hidden])
Date: 2009-11-11 13:35:13


2009/11/11 Emanuele Rocci <rocciemanuele_at_[hidden]>

>
> HI Roman!
> Thanks for your nice response!
> I have just discovered another way.
> Please give me your comments!
>
> constant_type< const char[7] >::type _name(constant("value: "));
>
> playing the same role of
>
> boost::function<const char*()> _name = boost::lambda::constant("value: ");
>
> I find both 2 nice ways of expressing constant string in a lamda expression.
>
>
> Using the boost::function approach, some sample code can be written like the following
> using round brackets next to _name variable.
>
> std::for_each( myList.begin(),myList.end(),(
> std::cout << _name() << _1 ,
> _1 = 2
> ));
>
>
This does not do what you think it does. It'll evaluate and output _name()
only once. Here's how you can fix it:

std::for_each( myList.begin(),myList.end(),(
        std::cout << bind(_name) << _1 ,
         _1 = 2
            ));

> I find the approach using boost::function very nice since it provides
> more the "genericity" feeling; you don't have to declare the size of the
> string but it is enough const char*().
>
> With the constant_type way it is possible to use _name as a common const variable without
> using round brackets
>
> std::for_each( myList.begin(),myList.end(),(
> std::cout << _name << _1 ,
> _1 = 2
> ));
>
>
This works as expected -- _name is being output several times.

> This works fine provided that the size is correct; it is probably not always nice,
> but compiler will complain if the size is not correct i.e. if you use const char[6]
> or if you use const char[8].
>
> Now I am wondering which is the fastest approach. I guess that probably they are
> the same.
>
>
Using constant_type should be faster, because it does not use virtual
functions. Also, to my surprise, it's a documented way of creating lazy
constants (see
http://www.boost.org/doc/libs/1_40_0/doc/html/lambda/le_in_details.html#lambda.delaying_constants_and_variables
).

Roman Perepelitsa.



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