Boost logo

Boost Users :

Subject: Re: [Boost-users] [tuple] Tuple arithmetic
From: Philipp Moeller (philipp.moeller_at_[hidden])
Date: 2012-02-10 03:50:33


Bill Buklis <boostusr_at_[hidden]> writes:

> 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};

Using a tuple this way is probably not the best idea. Tuples are
intended for heterogeneous types. If all you really want is a fixed
length container for doubles you should use boost/std::array<double>.

If you really insist on the tuple, here is

tuple_for_each isn't that hard:

template<class T, class F>
inline void for_each(boost::tuples::cons<T, boost::tuples::null_type>
const& tuple, F f)
{
     f(tuple.get_head());
}

template<class T, class U, class F>
inline void for_each(boost::tuples::cons<T, U> const& tuple, F f)
{
     f(tuple.get_head());
     for_each(tuple.get_tail(), f);
}

double a, b;
for_each(tie(a,b), [](double& x) { x *= 10.0; })

HTH,
Philipp Moeller


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