Boost logo

Boost Users :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2004-12-21 14:34:23


David Abrahams writes:
> Aleksey Gurtovoy wrote:
>
> > Answering the OP question: MPL lambda expressions do not support
> > scopes (yet), so it's not possible to implement the above without
> > an auxiliary metafunction incapsulating the nested scope. Which
> > actually might be a good thing -- it's hard to imagine that the
> > "inline" version would be shorter and easier to understand than
> > this:
> >
> > template< typename Map, typename Entry >
> > struct copy_entires
> > : copy<
> > typename Entry::second::entries
> > , inserter<Map, insert<_1,_2> >
> > >
> > {
> > };
> >
> > typedef fold<map_types, map_types, copy_entires<_1,_2> >::type result;
>
> In that case, can you explain what protect<> is for?

>From http://www.boost.org/libs/mpl/doc/refmanual/protect.html:

    'protect' is an identity wrapper for a Metafunction Class that
    prevents its argument from being recognized as a bind expression.

Actually, the above definition is incomplete; should be:

    'protect' is an identity wrapper for a Metafunction Class that
    prevents its argument from being recognized as a bind/placeholder
    expression.

The main usage for 'protect' is to prevent parametrized metafunction classes
from being accidentally treated as a placeholder expression simply because
their arguments happened to embed a placeholder. For instance:

    template< typename Predicate > struct next_if
    {
        template< typename N, typename T >
        struct apply
            : eval_if<
                  typename apply1<Predicate,T>::type
                , next<N>
                , identity<N>
>
        {
        };
    };

    template<
          typename Sequence
        , typename Predicate
>
    struct count_if
        : fold< Sequence, int_<0>, protect< next_if<Predicate> > >::type
    {
    };

Without 'protect', we'd have to pass 'Predicate' through 'lambda' before
using it to parametrize 'next_if', or the whole thing would break on
something like

    typedef count_if<numbers, less<_1,int_<0> > >::type r;

P.S. Please ignore the 'protect' example at the end of the page -- it's
a total garbage :(.

--
Aleksey Gurtovoy
MetaCommunications Engineering

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