Boost logo

Boost :

Subject: Re: [boost] [local] Help for the Alternatives section
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2011-03-27 09:59:29


On Sat, Mar 26, 2011 at 6:19 PM, Lorenzo Caminiti <lorcaminiti_at_[hidden]> wrote:
> How can I program the following code (its local function and `factor`
> constant binding) using Boost.Phoenix, Boost.Lambda, and C++0x lambda

***Thanks for the examples but is there a way to make `factor` const
in the closure?***

Local functions can do that by `const bind factor` (const value) or
`const bind& factor` (const reference). How about Boost.Lambda,
Boost.Phoenix, and C++0x lambda?

For example, why C++0x doesn't allow the use of const in the closure?
Was this proposed to the standard committee?

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    double sum = 0.0;
    int factor = 10;

    std::vector<double> v(3);
    v[0] = 1.0; v[1] = 2.0; v[2] = 3.0;

    // NOTE `const&` for factor (but not supported by C++0x).
    std::for_each(v.begin(), v.end(), [&sum, const &factor](double num) {
        sum += factor * num;
        std::cout << "Summed: " << sum << std::endl;
    });

    std::cout << sum << std::endl;
    return 0;
}

> functions? If you know, can you please reply with the actual code?
>
> #include <boost/local/function.hpp>
> #include <iostream>
> #include <vector>
> #include <algorithm>
>
> int main() {
>    double sum = 0.0;
>    int factor = 10;
>
>    void BOOST_LOCAL_FUNCTION_PARAMS(double num,
>            // Variable `factor` bound as constant.
>            bind& sum, const bind& factor) {
>        sum += factor * num;
>        std::cout << "Summed: " << sum << std::endl;
>    } BOOST_LOCAL_FUNCTION_NAME(add)
>
>    std::vector<double> v(3);
>    v[0] = 1.0; v[1] = 2.0; v[2] = 3.0;
>    // Local function `add` passed as template parameter.
>    std::for_each(v.begin(), v.end(), add);
>    return 0;
> }

Thanks.

--
Lorenzo

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk