Boost MPL Placeholders and Lambda
Asked Answered
E

1

11

I am currently doing some proof on concept samples with boost::mpl and am having some difficulties in understanding how the lambda function enables the use of placeholders.

I realize that I can wrap metafunctions in metafunction classes to enable higher order functions to be able to access the nested apply function, and have realised that you can avoid this effort by using mpl::lambda wrapping the metafunction which allows place holders.

How does this actually work? I am having trouble wrapping my head around what lamda and placeholders actually do under the covers.

Earthenware answered 23/4, 2012 at 3:16 Comment(0)
V
13

See the Boost.MPL manual: a placeholder is a metafunction class of the form mpl::arg<X>. A metafunction class is a class containing an apply metafunction.

template <int N> struct arg; // forward declarations
struct void_;

template <>
struct arg<1>
{
    template <
      class A1, class A2 = void_, ... class Am = void_>
    struct apply
    {
        typedef A1 type; // return the first argument
    };
};
typedef arg<1> _1

It's the job of mpl::lambda to turn placeholder expressions into metafunction classes. This is done by embedding a metafunction class like this:

template<
      typename X
    , typename Tag = unspecified
    >
struct lambda
{
    typedef unspecified type;
};

If x is a Placeholder Expression in a general form X<a1,...an>, where X is a class template and a1,... an are arbitrary types, the embedded unspecified type f is equivalent to

typedef protect< bind<
      quoten<X>
    , lambda<a1>::type,... lambda<an>::type
> > f;

otherwise, f is identical to X. The apply metafunction evaluates a lambda expression by accessing the embedded type.

In the MPL manual you can lookup the definitions of protect, bind and quote as well. They are all wrappers around their arguments to delay evaluation as long as possible.

Vikkivikky answered 24/4, 2012 at 14:16 Comment(2)
Clear and concise answer - should have been accepted by the OP.Drakensberg
Thanks, glad to have been of help!Vikkivikky

© 2022 - 2024 — McMap. All rights reserved.