Boost logo

Boost :

Subject: Re: [boost] [local] Help for the Alternatives section
From: Thomas Heller (thom.heller_at_[hidden])
Date: 2011-03-27 09:38:26


On Sunday, March 27, 2011 03:48:11 PM Lorenzo Caminiti wrote:
> On Sat, Mar 26, 2011 at 8:05 PM, Michael Caisse
> <boost_at_[hidden]> wrote:
> > On 03/26/2011 04:46 PM, Steven Watanabe wrote:
> >>
> >> AMDG
> >>
> >> On 03/26/2011 04:27 PM, Michael Caisse wrote:
> >>>
> >>> #include <boost/phoenix/phoenix.hpp>
> >>> #include <boost/phoenix/statement.hpp>
> >>> #include <iostream>
> >>> #include <vector>
> >>> #include <algorithm>
> >>>
> >>> int main() {
> >>> double sum = 0.0;
> >>> int factor = 10;
> >>>
> >>> using namespace boost::phoenix;
> >>> using namespace boost::phoenix::placeholders;
> >>>
> >>> std::vector<double> v(3);
> >>> v[0] = 1.0; v[1] = 2.0; v[2] = 3.0;
> >>> std::for_each(v.begin(), v.end(), (
> >>> ref(sum) += factor * _1,
> >>> std::cout << "Summed: " << ref(sum) << "\n" )
> >>> );
> >>> return 0;
> >>> }
> >>>
> >>
> >> This is incorrect. std::cout << "Summed: " is evaluated
> >> eagerly.
> >>
> >> In Christ,
> >> Steven Watanabe
> >
> > Sorry about that:
> >
> > std::cout << val("Summed: ") << ref(sum) << "\n"
> >
> >
> > or one of the other possibilities will do fine.
>
> I tried this but it didn't work... why?
>
> #include <boost/spirit/include/qi.hpp>
> #include <boost/spirit/include/phoenix_core.hpp>
> #include <boost/spirit/include/phoenix_operator.hpp>
> #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;
>
> std::for_each(v.begin(), v.end(), (
> boost::phoenix::ref(sum) += factor * boost::spirit::qi::_1,
                                               ~~~~~~~~~~~~~~~~~~~~~
This is not the same as boost::phoenix::arg_names::_1. I wonder why it compiled
at all.

> std::cout << boost::phoenix::val("Summed: ") <<
> boost::phoenix::ref(sum) << "\n"
> ));
>
> std::cout << sum << std::endl;
> return 0;
> }

Correct version is:

#include <boost/phoenix/phoenix.hpp>
// For Phoenix V2 uncomment this line, and comment the above:
#include <boost/spirit/include/phoenix.hpp>
#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;

    std::for_each(v.begin(), v.end(), (
        boost::phoenix::ref(sum) += factor * boost::phoenix::arg_names::_1,
        std::cout << boost::phoenix::val("Summed: ") <<
                boost::phoenix::ref(sum) << "\n"
    ));

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


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