Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2003-01-06 06:44:47


Greg Colvin wrote:
> > > If this construct applies a metafuntion to a sequence
> >
> > It does and it doesn't :). Sorry if I wasn't clear about the
> > semantics; it does not apply a metafunction to every element
> > of a sequence;
>
> That would be for_each ?

Almost - 'for_each' only makes sense if a (meta)function being called is
allowed to have side effects; since a pure compile-time metafunction isn't
(cannot), we don't have a pure compile-time 'for_each'. Instead, we have a
whole family of 'fold' algorithms
(http://www.mywikinet.com/mpl/ref/Algorithms.html), e.g.:

    typedef fold< numbers, int_c<0>, plus<_1,_2> >::type sum;

What we do have on the 'for_each' side, is a "half run-time" algorithm that
invokes an ordinary function on each element of a compile-time sequence:

    typedef mpl::range_c<int,0,10> numbers;
    std::vector<int> v;
    mpl::for_each<numbers>(
          boost::bind(&std::vector<int>::push_back, &v, _1)
        );

    // equivalent to
    // v.push_back(0);
    // v.push_back(1);
    // ...
    // v.push_back(9);

> > Yeah, unfortunately it can't be. You have to have different
> > notation for invoking a function with a sequence of elements,
> > 'cause just determining if the first and the only argument is
> > a sequence and unrolling it is not enough - a (meta)function
> > itself might expect exactly the original sequence, after all.
>
> Yep. Is there no way to use function call syntax for the
> 0...n args case?

As a matter of fact, it is, well, kind of:

    invoke< f(int,long) >::type // 'f' is a metafunction class here

The only problem with the above is that it doesn't support certain types of
argument very well (as highlighted in here:
http://www.mail-archive.com/boost@lists.boost.org/msg00705.html), so when
passing const, array, or 'void' types to a metafunction invoked in this
manner, one has to do something like this:

    invoke< f(arg<int const>,long) >::type

And it's not as portable as one would wish (for instance, gcc 3.2 chokes on
some of those, not to speak about the other less capable compilers out
there), so the combination of these factors pretty much rules it out, at
least for now.

Aleksey


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