...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 / Lambda Details / Placeholders |
The definition of "placeholder" may surprise you:
Definition
A placeholder is a metafunction class of the form mpl::arg<X>.
The convenient names _1, _2,... _5 are actually typedefs for specializations of mpl::arg that simply select the Nth argument for any N. [6] The implementation of placeholders looks something like this:
[6] | MPL provides five placeholders by default. See the Configuration Macros section of the MPL reference manual for a description of how to change the number of placeholders provided. |
namespace boost { namespace mpl { namespace placeholders { 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; template <> struct arg<2> { template < class A1, class A2, class A3 = void_, ...class Am = void_ > struct apply { typedef A2 type; // return the second argument }; }; typedef arg<2> _2; more specializations and typedefs... }}}
Remember that invoking a metafunction class is the same as invoking its nested apply metafunction. When a placeholder in a lambda expression is evaluated, it is invoked on the expression's actual arguments, returning just one of them. The results are then substituted back into the lambda expression and the evaluation process continues.
There's one special placeholder, known as the unnamed placeholder, that we haven't yet defined:
namespace boost { namespace mpl { namespace placeholders { typedef arg<-1> _; // the unnamed placeholder }}}
The details of its implementation aren't important; all you really need to know about the unnamed placeholder is that it gets special treatment. When a lambda expression is being transformed into a metafunction class by mpl::lambda,
the nth appearance of the unnamed placeholder in a given template specialization is replaced with _n.
So, for example, every row of Table 1.1 below contains two equivalent lambda expressions.
mpl::plus<_,_> |
mpl::plus<_1,_2> |
boost::is_same< _ , boost::add_pointer<_> > |
boost::is_same< _1 , boost::add_pointer<_1> > |
mpl::multiplies< mpl::plus<_,_> , mpl::minus<_,_> > |
mpl::multiplies< mpl::plus<_1,_2> , mpl::minus<_1,_2> > |
Especially when used in simple lambda expressions, the unnamed placeholder often eliminates just enough syntactic "noise" to significantly improve readability.