Boost logo

Boost Users :

From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2002-04-26 12:37:25


Toon Knapen wrote:
> I have a list of heterogeneous objects, e.g.
>
> struct Foo {
> Foo(int v) : value_( v ) {}
> int value() const { return value_ ; }
> int value_;
> };
>
> struct Bar {
> Bar(int v) : value_( v ) {}
> int value() const { return value_ ; }
> int value_;
> };
>
> int main()
> {
> Foo foo(3);
> Bar bar(7);
> typedef boost::tuple< Foo, Bar > MyTuple ;
> MyTuple my_tuple( foo, bar );
> return 0;
> }
>
> And now I want to have a function that can accumulate the
> value sof all the objects in the tuple, e.g. (pseudocode since
> my problem is exacly that I can't figure out how to code this)
>
> template < typename TypleType >
> int accumulate_values(const TupleType& t)
> {
> int acc = 0;
> for(int i = 0 ; i < t.size() ; ++i ) acc += (get< i >( t )).value();
> }
>
> Can I do this using mpl (mpl looks great but I can't figure
> out how to do this).

It's not exactly a part of MPL (the library doesn't target "run-time" stuff
to that extent yet; I hope it will some day), but "tuple extension"
components I wrote some time ago
(http://groups.yahoo.com/group/boost/files/tuple_ext/tuple_ext-08-nov-01.zip
) allow one to do exactly these kinds of things:

    // untested! :)
    template< typename Seq, typename T, typename BinaryOp >
    T accumulate(Seq const& s, T const& Init, BinaryOp op)
    {
        T result = Init;
        for_each(
              begin(s)
            , end(s)
            , boost::bind<T>(op, boost::ref(result), _1)
            );

        return result;
    }

With the above, you can do something like this:

    struct get_value
    {
        template< typename T >
        int operator()(T const& x) const
        {
            return x.value();
        }
    };

    int sum = accumulate(
          tuple
        , 0
        , boost::bind(std::plus<int>()
            , _1
            , boost::bind<int>(get_value(),_2)
            )
        );

Hope it's not too complicated :). LL might allow to do better on this one.

Aleksey


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