From: Arkadiy Vertleyb (vertleyb_at_[hidden])
Date: 2004-07-01 22:17:08


"Dan" <dan_at_[hidden]> wrote

> How does this _1 and _2 stuff work anyway?

>From my experience, in order to understand this stuff, you first have to
temporarily forget about _1 and _2 (unless you are already fluent with
Boost.Lambda).

An MPL algorithm (fold, iter_fold, etc.) actually accepts 3 parameters:

1) sequence;
2) initial type (state);
3) metafunction class.

The third parameter defines how to create a new state from the old state and
the current element (or iterator) of the sequence, for your example
something like this:

struct adder
{
    template<class State, class Current>
    struct apply
    {
        typedef typename mpl::plus<State, Current>::type type;
    };
};

(this may not compile -- I am not sure about the order of template
parameters)

The adder is analogous to a functor in STL, and apply is analogous to the
function call operator.

Having defined this "functor", you can get your result something like this:

typedef mpl::fold<MySequence, mpl::int_<0>, adder>::type MyResult;

As far as _1, _2, etc., is concerned -- this is MPL Lambda facility, it
allows to define metafunction classes right in-place, in the same way
Boost.Lambda does for runtime functors. I believe (I may be wrong of
course) that MPL Lambda is more complicated than the rest of MPL, but, in
short, _1 stands for the first parameter of apply, and _2 -- for the second
parameter.

When you write:

mpl::plus<mpl::_2, mpl::_1>

this effectively (by the means of MPL Lambda) defines a metafunction class
("functor") that acts in the same way as the "adder" does.

HTH,
Arkadiy