Boost logo

Boost :

Subject: Re: [boost] [local] Help for the Alternatives section
From: lcaminiti (lorcaminiti_at_[hidden])
Date: 2011-05-04 14:43:48


Mathias Gaunard-2 wrote:
>
> 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.
>

I see.

>> 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.
>

Yes, I did think of it but only after I sent the email :)

>> 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.
>

Can I do this without auto? Otherwise, the local Phoenix function retains
its polymorphic behavior only on C++0x (but not on ISO C++) when it is given
a name by assigning it to a local variable like local_add.

Thanks a lot again.
--Lorenzo

--
View this message in context: http://boost.2283326.n4.nabble.com/local-Help-for-the-Alternatives-section-tp3408469p3496443.html
Sent from the Boost - Dev mailing list archive at Nabble.com.

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