Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Front Page / Tutorial: Metafunctions and Higher-Order Metaprogramming / Handling Placeholders / The apply Metafunction

The apply Metafunction

Invoking the result of lambda is such a common pattern that MPL provides an apply metafunction to do just that. Using mpl::apply, our flexible version of twice becomes:

#include <boost/mpl/apply.hpp>

template <class F, class X>
struct twice
   : mpl::apply<F, typename mpl::apply<F,X>::type>
{};

You can think of mpl::apply as being just like the apply1 template that we wrote, with two additional features:

  1. While apply1 operates only on metafunction classes, the first argument to mpl::apply can be any lambda expression (including those built with placeholders).

  2. While apply1 accepts only one additional argument to which the metafunction class will be applied, mpl::apply can invoke its first argument on any number from zero to five additional arguments. [5] For example:

    // binary lambda expression applied to 2 additional arguments
    mpl::apply<
        mpl::plus<_1,_2>   
      , mpl::int_<6>
      , mpl::int_<7>
    >::type::value // == 13
    
[5]See the Configuration Macros section of the the MPL reference manual for a description of how to change the maximum number of arguments handled by mpl::apply.

Guideline

When writing a metafunction that invokes one of its arguments, use mpl::apply so that it works with lambda expressions.