Boost logo

Boost Users :

Subject: Re: [Boost-users] [tuple] Tuple arithmetic
From: Jeffrey Lee Hellrung, Jr. (jeffrey.hellrung_at_[hidden])
Date: 2012-02-09 21:11:03


On Thu, Feb 9, 2012 at 5:46 PM, Bill Buklis <boostusr_at_[hidden]> wrote:

> Is there any facility to perform arithmetic operations on a tuple?
>
> For example:
>
> struct data
> {
> double a, b;
> };
>
> data d1 = {1.0, 2.0};
> data d2 = {2.5, 5.5};
>
> // These two lines are not valid, but simulate what I want.
> boost::tie(d1.a, d1.b) *= 10.0; // Multiply each element by 10.0
> boost::tie(d1.a, d1.b) += boost::tie(d2.a, d2.b); // Add the
> elements from the second object
>
> After calculations, d1 should equal {12.5, 25.5};
>

Boost.Fusion + Boost.Phoenix *might* be what you're looking for, but I
don't know.

Specifically, boost::fusion::for_each [1] lets you iterate over a tuple and
apply a (polymorphic) function to each element; that function can be built
inline using Boost.Phoenix. E.g., (untested)

boost::fusion::for_each(d1, boost::phoenix::arg_names::_1 *= 10.0);

Your second example above might be a bit more verbose using these
techniques. Check out also boost::fusion::transform [2] and, maybe,
boost::fusion::zip_view [3]? Also, you'll have to adapt [4] your data
struct to be recognizable as a Boost.Fusion sequence.

[1]
http://www.boost.org/doc/libs/1_48_0/libs/fusion/doc/html/fusion/algorithm/iteration/functions/for_each.html
[2]
http://www.boost.org/doc/libs/1_48_0/libs/fusion/doc/html/fusion/algorithm/transformation/functions/transform.html
[3]
http://www.boost.org/doc/libs/1_48_0/libs/fusion/doc/html/fusion/view/zip_view.html
[4]
http://www.boost.org/doc/libs/1_48_0/libs/fusion/doc/html/fusion/adapted/adapt_struct.html

- Jeff



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