Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

3.4 More Lambda Capabilities

Lambda expressions provide much more than just the ability to pass a metafunction as an argument. The two capabilities described next combine to make lambda expressions an invaluable part of almost every metaprogramming task.

3.4.1 Partial Metafunction Application

Consider the lambda expression mpl::plus<_1,_1>. A single argument is directed to both of plus's parameters, thereby adding a number to itself. Thus, a binary metafunction, plus, is used to build a unary lambda expression. In other words, we've created a whole new computation! We're not done yet, though: By supplying a non-placeholder as one of the arguments, we can build a unary lambda expression that adds a fixed value, say 42, to its argument:

    mpl::plus<_1, mpl::int_<42> >

The process of binding argument values to a subset of a function's parameters is known in the world of functional programming as partial function application.

3.4.2 Metafunction Composition

Lambda expressions can also be used to assemble more interesting computations from simple metafunctions. For example, the following expression, which multiplies the sum of two numbers by their difference, is a composition of the three metafunctions multiplies, plus, and minus:

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

When evaluating a lambda expression, MPL checks to see if any of its arguments are themselves lambda expressions, and evaluates each one that it finds. The results of these inner evaluations are substituted into the outer expression before it is evaluated.

  • + Share This
  • 🔖 Save To Your Account