Boost logo

Boost :

Subject: Re: [boost] [local] Help for the Alternatives section
From: Mathias Gaunard (mathias.gaunard_at_[hidden])
Date: 2011-05-04 13:31:43


On 03/05/2011 21:44, lcaminiti wrote:

> For example, it would be useful to program a polymorphic global functor to
> add a vector of doubles and ints using the same global_add algorithm
> (without duplicating the code to implement two different algorithms):

Or for more advanced things.
Consider a generic algorithm such as fold (accumulate). Now consider
another generic algorithm (transform, for_each, whatever) defined in
terms of fold.
It needs to pass a polymorphic function object to fold in order to be
generic.

> template<typename T>
> struct global_add {
> global_add(double& _sum, const int& _factor): sum(_sum), factor(_factor)
> {}
> inline void operator()(T num) {
> sum += factor * num;
> }
> private:
> double& sum;
> const int& factor;
> };

I'd put the template<typename T> on the operator() to avoid having to
specify it.

> int main() {
> double sum = 0.0;
> int factor = 10;
>
> __some_local_template_type__ local_add = let(_f = cref(factor))[
> ref(sum) += _f * _1
> ];
>
> std::vector<double> v(3);
> v[0] = 1.0; v[1] = 2.0; v[2] = 3.0;
> std::for_each(v.begin(), v.end(), local_add<double>(sum, factor));
>
> std::vector<int> w(3);
> w[0] = -1; w[1] = -2; w[2] = -3;
> std::for_each(w.begin(), w.end(), local_add<int>(sum, factor));
>
> std::cout<< sum<< std::endl;
> return 0;
> }
>

> Is there a way to do this or something similar with Boost.Phoenix (or
> Boost.Lambda)?

std::vector<double> v(3);
std::for_each(v.begin(), v.end(), ref(sum) += factor * _1);

std::vector<int> w(3);
std::for_each(w.begin(), w.end(), ref(sum) += factor * _1);

or if you want to avoid repetition,

auto local_add = ref(sum) += factor * _1;

std::vector<double> v(3);
std::for_each(v.begin(), v.end(), local_add);

std::vector<int> w(3);
std::for_each(w.begin(), w.end(), local_add);

Note you need auto, since using type erasure would force the function
object to be monomorphic.


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