1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2<html> 3<head> 4<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5<title>Lambda expressions in details</title> 6<link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css"> 7<meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> 8<link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> 9<link rel="up" href="../lambda.html" title="Chapter 20. Boost.Lambda"> 10<link rel="prev" href="using_library.html" title="Using the library"> 11<link rel="next" href="extending.html" title="Extending return type deduction system"> 12</head> 13<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> 14<table cellpadding="2" width="100%"><tr> 15<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td> 16<td align="center"><a href="../../../index.html">Home</a></td> 17<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td> 18<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> 19<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> 20<td align="center"><a href="../../../more/index.htm">More</a></td> 21</tr></table> 22<hr> 23<div class="spirit-nav"> 24<a accesskey="p" href="using_library.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lambda.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="extending.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> 25</div> 26<div class="section"> 27<div class="titlepage"><div><div><h2 class="title" style="clear: both"> 28<a name="lambda.le_in_details"></a>Lambda expressions in details</h2></div></div></div> 29<div class="toc"><dl class="toc"> 30<dt><span class="section"><a href="le_in_details.html#lambda.placeholders">Placeholders</a></span></dt> 31<dt><span class="section"><a href="le_in_details.html#lambda.operator_expressions">Operator expressions</a></span></dt> 32<dt><span class="section"><a href="le_in_details.html#lambda.bind_expressions">Bind expressions</a></span></dt> 33<dt><span class="section"><a href="le_in_details.html#lambda.overriding_deduced_return_type">Overriding the deduced return type</a></span></dt> 34<dt><span class="section"><a href="le_in_details.html#lambda.delaying_constants_and_variables">Delaying constants and variables</a></span></dt> 35<dt><span class="section"><a href="le_in_details.html#lambda.lambda_expressions_for_control_structures">Lambda expressions for control structures</a></span></dt> 36<dt><span class="section"><a href="le_in_details.html#lambda.exceptions">Exceptions</a></span></dt> 37<dt><span class="section"><a href="le_in_details.html#lambda.construction_and_destruction">Construction and destruction</a></span></dt> 38<dt><span class="section"><a href="le_in_details.html#id-1.3.21.7.11">Special lambda expressions</a></span></dt> 39<dt><span class="section"><a href="le_in_details.html#id-1.3.21.7.12">Casts, sizeof and typeid</a></span></dt> 40<dt><span class="section"><a href="le_in_details.html#lambda.nested_stl_algorithms">Nesting STL algorithm invocations</a></span></dt> 41</dl></div> 42<p> 43This section describes different categories of lambda expressions in details. 44We devote a separate section for each of the possible forms of a lambda expression. 45 46 47</p> 48<div class="section"> 49<div class="titlepage"><div><div><h3 class="title"> 50<a name="lambda.placeholders"></a>Placeholders</h3></div></div></div> 51<p> 52The BLL defines three placeholder types: <code class="literal">placeholder1_type</code>, <code class="literal">placeholder2_type</code> and <code class="literal">placeholder3_type</code>. 53BLL has a predefined placeholder variable for each placeholder type: <code class="literal">_1</code>, <code class="literal">_2</code> and <code class="literal">_3</code>. 54However, the user is not forced to use these placeholders. 55It is easy to define placeholders with alternative names. 56This is done by defining new variables of placeholder types. 57For example: 58 59</p> 60<pre class="programlisting">boost::lambda::placeholder1_type X; 61boost::lambda::placeholder2_type Y; 62boost::lambda::placeholder3_type Z; 63</pre> 64<p> 65 66With these variables defined, <code class="literal">X += Y * Z</code> is equivalent to <code class="literal">_1 += _2 * _3</code>. 67</p> 68<p> 69The use of placeholders in the lambda expression determines whether the resulting function is nullary, unary, binary or 3-ary. 70The highest placeholder index is decisive. For example: 71 72</p> 73<pre class="programlisting"> 74_1 + 5 // unary 75_1 * _1 + _1 // unary 76_1 + _2 // binary 77bind(f, _1, _2, _3) // 3-ary 78_3 + 10 // 3-ary 79</pre> 80<p> 81 82Note that the last line creates a 3-ary function, which adds <code class="literal">10</code> to its <span class="emphasis"><em>third</em></span> argument. 83The first two arguments are discarded. 84Furthermore, lambda functors only have a minimum arity. 85One can always provide more arguments (up the number of supported placeholders) 86that is really needed. 87The remaining arguments are just discarded. 88For example: 89 90</p> 91<pre class="programlisting"> 92int i, j, k; 93_1(i, j, k) // returns i, discards j and k 94(_2 + _2)(i, j, k) // returns j+j, discards i and k 95</pre> 96<p> 97 98See 99<a class="xref" href="s10.html#lambda.why_weak_arity" title="Lambda functor arity">the section called “ 100Lambda functor arity 101”</a> for the design rationale behind this 102functionality. 103 104</p> 105<p> 106In addition to these three placeholder types, there is also a fourth placeholder type <code class="literal">placeholderE_type</code>. 107The use of this placeholder is defined in <a class="xref" href="le_in_details.html#lambda.exceptions" title="Exceptions">the section called “Exceptions”</a> describing exception handling in lambda expressions. 108</p> 109<p>When an actual argument is supplied for a placeholder, the parameter passing mode is always by reference. 110This means that any side-effects to the placeholder are reflected to the actual argument. 111For example: 112 113 114</p> 115<pre class="programlisting"> 116int i = 1; 117(_1 += 2)(i); // i is now 3 118(++_1, cout << _1)(i) // i is now 4, outputs 4 119</pre> 120<p> 121</p> 122</div> 123<div class="section"> 124<div class="titlepage"><div><div><h3 class="title"> 125<a name="lambda.operator_expressions"></a>Operator expressions</h3></div></div></div> 126<div class="toc"><dl class="toc"> 127<dt><span class="section"><a href="le_in_details.html#id-1.3.21.7.4.4">Operators that cannot be overloaded</a></span></dt> 128<dt><span class="section"><a href="le_in_details.html#lambda.assignment_and_subscript">Assignment and subscript operators</a></span></dt> 129<dt><span class="section"><a href="le_in_details.html#lambda.logical_operators">Logical operators</a></span></dt> 130<dt><span class="section"><a href="le_in_details.html#lambda.comma_operator">Comma operator</a></span></dt> 131<dt><span class="section"><a href="le_in_details.html#lambda.function_call_operator">Function call operator</a></span></dt> 132<dt><span class="section"><a href="le_in_details.html#lambda.member_pointer_operator">Member pointer operator</a></span></dt> 133</dl></div> 134<p> 135The basic rule is that any C++ operator invocation with at least one argument being a lambda expression is itself a lambda expression. 136Almost all overloadable operators are supported. 137For example, the following is a valid lambda expression: 138 139</p> 140<pre class="programlisting">cout << _1, _2[_3] = _1 && false</pre> 141<p> 142</p> 143<p> 144However, there are some restrictions that originate from the C++ operator overloading rules, and some special cases. 145</p> 146<div class="section"> 147<div class="titlepage"><div><div><h4 class="title"> 148<a name="id-1.3.21.7.4.4"></a>Operators that cannot be overloaded</h4></div></div></div> 149<p> 150Some operators cannot be overloaded at all (<code class="literal">::</code>, <code class="literal">.</code>, <code class="literal">.*</code>). 151For some operators, the requirements on return types prevent them to be overloaded to create lambda functors. 152These operators are <code class="literal">->.</code>, <code class="literal">-></code>, <code class="literal">new</code>, <code class="literal">new[]</code>, <code class="literal">delete</code>, <code class="literal">delete[]</code> and <code class="literal">?:</code> (the conditional operator). 153</p> 154</div> 155<div class="section"> 156<div class="titlepage"><div><div><h4 class="title"> 157<a name="lambda.assignment_and_subscript"></a>Assignment and subscript operators</h4></div></div></div> 158<p> 159These operators must be implemented as class members. 160Consequently, the left operand must be a lambda expression. For example: 161 162</p> 163<pre class="programlisting"> 164int i; 165_1 = i; // ok 166i = _1; // not ok. i is not a lambda expression 167</pre> 168<p> 169 170There is a simple solution around this limitation, described in <a class="xref" href="le_in_details.html#lambda.delaying_constants_and_variables" title="Delaying constants and variables">the section called “Delaying constants and variables”</a>. 171In short, 172the left hand argument can be explicitly turned into a lambda functor by wrapping it with a special <code class="literal">var</code> function: 173</p> 174<pre class="programlisting"> 175var(i) = _1; // ok 176</pre> 177<p> 178 179</p> 180</div> 181<div class="section"> 182<div class="titlepage"><div><div><h4 class="title"> 183<a name="lambda.logical_operators"></a>Logical operators</h4></div></div></div> 184<p> 185Logical operators obey the short-circuiting evaluation rules. For example, in the following code, <code class="literal">i</code> is never incremented: 186</p> 187<pre class="programlisting"> 188bool flag = true; int i = 0; 189(_1 || ++_2)(flag, i); 190</pre> 191<p> 192</p> 193</div> 194<div class="section"> 195<div class="titlepage"><div><div><h4 class="title"> 196<a name="lambda.comma_operator"></a>Comma operator</h4></div></div></div> 197<p> 198Comma operator is the <span class="quote">“<span class="quote">statement separator</span>”</span> in lambda expressions. 199Since comma is also the separator between arguments in a function call, extra parenthesis are sometimes needed: 200 201</p> 202<pre class="programlisting"> 203for_each(a.begin(), a.end(), (++_1, cout << _1)); 204</pre> 205<p> 206 207Without the extra parenthesis around <code class="literal">++_1, cout << _1</code>, the code would be interpreted as an attempt to call <code class="literal">for_each</code> with four arguments. 208</p> 209<p> 210The lambda functor created by the comma operator adheres to the C++ rule of always evaluating the left operand before the right one. 211In the above example, each element of <code class="literal">a</code> is first incremented, then written to the stream. 212</p> 213</div> 214<div class="section"> 215<div class="titlepage"><div><div><h4 class="title"> 216<a name="lambda.function_call_operator"></a>Function call operator</h4></div></div></div> 217<p> 218The function call operators have the effect of evaluating the lambda 219functor. 220Calls with too few arguments lead to a compile time error. 221</p> 222</div> 223<div class="section"> 224<div class="titlepage"><div><div><h4 class="title"> 225<a name="lambda.member_pointer_operator"></a>Member pointer operator</h4></div></div></div> 226<p> 227The member pointer operator <code class="literal">operator->*</code> can be overloaded freely. 228Hence, for user defined types, member pointer operator is no special case. 229The built-in meaning, however, is a somewhat more complicated case. 230The built-in member pointer operator is applied if the left argument is a pointer to an object of some class <code class="literal">A</code>, and the right hand argument is a pointer to a member of <code class="literal">A</code>, or a pointer to a member of a class from which <code class="literal">A</code> derives. 231We must separate two cases: 232 233</p> 234<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> 235<li class="listitem"> 236<p>The right hand argument is a pointer to a data member. 237In this case the lambda functor simply performs the argument substitution and calls the built-in member pointer operator, which returns a reference to the member pointed to. 238For example: 239</p> 240<pre class="programlisting"> 241struct A { int d; }; 242A* a = new A(); 243 ... 244(a ->* &A::d); // returns a reference to a->d 245(_1 ->* &A::d)(a); // likewise 246</pre> 247<p> 248</p> 249</li> 250<li class="listitem"> 251<p> 252The right hand argument is a pointer to a member function. 253For a built-in call like this, the result is kind of a delayed member function call. 254Such an expression must be followed by a function argument list, with which the delayed member function call is performed. 255For example: 256</p> 257<pre class="programlisting"> 258struct B { int foo(int); }; 259B* b = new B(); 260 ... 261(b ->* &B::foo) // returns a delayed call to b->foo 262 // a function argument list must follow 263(b ->* &B::foo)(1) // ok, calls b->foo(1) 264 265(_1 ->* &B::foo)(b); // returns a delayed call to b->foo, 266 // no effect as such 267(_1 ->* &B::foo)(b)(1); // calls b->foo(1) 268</pre> 269<p> 270</p> 271</li> 272</ul></div> 273<p> 274</p> 275</div> 276</div> 277<div class="section"> 278<div class="titlepage"><div><div><h3 class="title"> 279<a name="lambda.bind_expressions"></a>Bind expressions</h3></div></div></div> 280<div class="toc"><dl class="toc"> 281<dt><span class="section"><a href="le_in_details.html#lambda.function_pointers_as_targets">Function pointers or references as targets</a></span></dt> 282<dt><span class="section"><a href="le_in_details.html#member_functions_as_targets">Member functions as targets</a></span></dt> 283<dt><span class="section"><a href="le_in_details.html#lambda.members_variables_as_targets">Member variables as targets</a></span></dt> 284<dt><span class="section"><a href="le_in_details.html#lambda.function_objects_as_targets">Function objects as targets</a></span></dt> 285</dl></div> 286<p> 287Bind expressions can have two forms: 288 289 290</p> 291<pre class="programlisting"> 292bind(<em class="parameter"><code>target-function</code></em>, <em class="parameter"><code>bind-argument-list</code></em>) 293bind(<em class="parameter"><code>target-member-function</code></em>, <em class="parameter"><code>object-argument</code></em>, <em class="parameter"><code>bind-argument-list</code></em>) 294</pre> 295<p> 296 297A bind expression delays the call of a function. 298If this <span class="emphasis"><em>target function</em></span> is <span class="emphasis"><em>n</em></span>-ary, then the <code class="literal"><span class="emphasis"><em>bind-argument-list</em></span></code> must contain <span class="emphasis"><em>n</em></span> arguments as well. 299In the current version of the BLL, 0 <= n <= 9 must hold. 300For member functions, the number of arguments must be at most 8, as the object argument takes one argument position. 301 302Basically, the 303<span class="emphasis"><em><code class="literal">bind-argument-list</code></em></span> must be a valid argument list for the target function, except that any argument can be replaced with a placeholder, or more generally, with a lambda expression. 304Note that also the target function can be a lambda expression. 305 306The result of a bind expression is either a nullary, unary, binary or 3-ary function object depending on the use of placeholders in the <span class="emphasis"><em><code class="literal">bind-argument-list</code></em></span> (see <a class="xref" href="le_in_details.html#lambda.placeholders" title="Placeholders">the section called “Placeholders”</a>). 307</p> 308<p> 309The return type of the lambda functor created by the bind expression can be given as an explicitly specified template parameter, as in the following example: 310</p> 311<pre class="programlisting"> 312bind<<span class="emphasis"><em>RET</em></span>>(<span class="emphasis"><em>target-function</em></span>, <span class="emphasis"><em>bind-argument-list</em></span>) 313</pre> 314<p> 315This is only necessary if the return type of the target function cannot be deduced. 316</p> 317<p> 318The following sections describe the different types of bind expressions. 319</p> 320<div class="section"> 321<div class="titlepage"><div><div><h4 class="title"> 322<a name="lambda.function_pointers_as_targets"></a>Function pointers or references as targets</h4></div></div></div> 323<p>The target function can be a pointer or a reference to a function and it can be either bound or unbound. For example: 324</p> 325<pre class="programlisting"> 326X foo(A, B, C); A a; B b; C c; 327bind(foo, _1, _2, c)(a, b); 328bind(&foo, _1, _2, c)(a, b); 329bind(_1, a, b, c)(foo); 330</pre> 331<p> 332 333The return type deduction always succeeds with this type of bind expressions. 334</p> 335<p> 336Note, that in C++ it is possible to take the address of an overloaded function only if the address is assigned to, or used as an initializer of, a variable, the type of which solves the amibiguity, or if an explicit cast expression is used. 337This means that overloaded functions cannot be used in bind expressions directly, e.g.: 338</p> 339<pre class="programlisting"> 340void foo(int); 341void foo(float); 342int i; 343 ... 344bind(&foo, _1)(i); // error 345 ... 346void (*pf1)(int) = &foo; 347bind(pf1, _1)(i); // ok 348bind(static_cast<void(*)(int)>(&foo), _1)(i); // ok 349</pre> 350<p> 351</p> 352</div> 353<div class="section"> 354<div class="titlepage"><div><div><h4 class="title"> 355<a name="member_functions_as_targets"></a>Member functions as targets</h4></div></div></div> 356<p> 357The syntax for using pointers to member function in bind expression is: 358</p> 359<pre class="programlisting"> 360bind(<em class="parameter"><code>target-member-function</code></em>, <em class="parameter"><code>object-argument</code></em>, <em class="parameter"><code>bind-argument-list</code></em>) 361</pre> 362<p> 363 364The object argument can be a reference or pointer to the object, the BLL supports both cases with a uniform interface: 365 366</p> 367<pre class="programlisting"> 368bool A::foo(int) const; 369A a; 370vector<int> ints; 371 ... 372find_if(ints.begin(), ints.end(), bind(&A::foo, a, _1)); 373find_if(ints.begin(), ints.end(), bind(&A::foo, &a, _1)); 374</pre> 375<p> 376 377Similarly, if the object argument is unbound, the resulting lambda functor can be called both via a pointer or a reference: 378 379</p> 380<pre class="programlisting"> 381bool A::foo(int); 382list<A> refs; 383list<A*> pointers; 384 ... 385find_if(refs.begin(), refs.end(), bind(&A::foo, _1, 1)); 386find_if(pointers.begin(), pointers.end(), bind(&A::foo, _1, 1)); 387</pre> 388<p> 389 390</p> 391<p> 392Even though the interfaces are the same, there are important semantic differences between using a pointer or a reference as the object argument. 393The differences stem from the way <code class="literal">bind</code>-functions take their parameters, and how the bound parameters are stored within the lambda functor. 394The object argument has the same parameter passing and storing mechanism as any other bind argument slot (see <a class="xref" href="using_library.html#lambda.storing_bound_arguments" title="Storing bound arguments in lambda functions">the section called “Storing bound arguments in lambda functions”</a>); it is passed as a const reference and stored as a const copy in the lambda functor. 395This creates some asymmetry between the lambda functor and the original member function, and between seemingly similar lambda functors. For example: 396</p> 397<pre class="programlisting"> 398class A { 399 int i; mutable int j; 400public: 401 402 A(int ii, int jj) : i(ii), j(jj) {}; 403 void set_i(int x) { i = x; }; 404 void set_j(int x) const { j = x; }; 405}; 406</pre> 407<p> 408 409When a pointer is used, the behavior is what the programmer might expect: 410 411</p> 412<pre class="programlisting"> 413A a(0,0); int k = 1; 414bind(&A::set_i, &a, _1)(k); // a.i == 1 415bind(&A::set_j, &a, _1)(k); // a.j == 1 416</pre> 417<p> 418 419Even though a const copy of the object argument is stored, the original object <code class="literal">a</code> is still modified. 420This is since the object argument is a pointer, and the pointer is copied, not the object it points to. 421When we use a reference, the behaviour is different: 422 423</p> 424<pre class="programlisting"> 425A a(0,0); int k = 1; 426bind(&A::set_i, a, _1)(k); // error; a const copy of a is stored. 427 // Cannot call a non-const function set_i 428bind(&A::set_j, a, _1)(k); // a.j == 0, as a copy of a is modified 429</pre> 430<p> 431</p> 432<p> 433To prevent the copying from taking place, one can use the <code class="literal">ref</code> or <code class="literal">cref</code> wrappers (<code class="literal">var</code> and <code class="literal">constant_ref</code> would do as well): 434</p> 435<pre class="programlisting"> 436bind(&A::set_i, ref(a), _1)(k); // a.j == 1 437bind(&A::set_j, cref(a), _1)(k); // a.j == 1 438</pre> 439<p> 440</p> 441<p>Note that the preceding discussion is relevant only for bound arguments. 442If the object argument is unbound, the parameter passing mode is always by reference. 443Hence, the argument <code class="literal">a</code> is not copied in the calls to the two lambda functors below: 444</p> 445<pre class="programlisting"> 446A a(0,0); 447bind(&A::set_i, _1, 1)(a); // a.i == 1 448bind(&A::set_j, _1, 1)(a); // a.j == 1 449</pre> 450<p> 451</p> 452</div> 453<div class="section"> 454<div class="titlepage"><div><div><h4 class="title"> 455<a name="lambda.members_variables_as_targets"></a>Member variables as targets</h4></div></div></div> 456<p> 457A pointer to a member variable is not really a function, but 458the first argument to the <code class="literal">bind</code> function can nevertheless 459be a pointer to a member variable. 460Invoking such a bind expression returns a reference to the data member. 461For example: 462 463</p> 464<pre class="programlisting"> 465struct A { int data; }; 466A a; 467bind(&A::data, _1)(a) = 1; // a.data == 1 468</pre> 469<p> 470 471The cv-qualifiers of the object whose member is accessed are respected. 472For example, the following tries to write into a const location: 473</p> 474<pre class="programlisting"> 475const A ca = a; 476bind(&A::data, _1)(ca) = 1; // error 477</pre> 478<p> 479 480</p> 481</div> 482<div class="section"> 483<div class="titlepage"><div><div><h4 class="title"> 484<a name="lambda.function_objects_as_targets"></a>Function objects as targets</h4></div></div></div> 485<p> 486 487Function objects, that is, class objects which have the function call 488operator defined, can be used as target functions. 489 490In general, BLL cannot deduce the return type of an arbitrary function object. 491 492However, there are two methods for giving BLL this capability for a certain 493function object class. 494 495</p> 496<div class="simplesect"> 497<div class="titlepage"><div><div><h5 class="title"> 498<a name="id-1.3.21.7.5.8.3"></a>The result_type typedef</h5></div></div></div> 499<p> 500 501The BLL supports the standard library convention of declaring the return type 502of a function object with a member typedef named <code class="literal">result_type</code> in the 503function object class. 504 505Here is a simple example: 506</p> 507<pre class="programlisting"> 508struct A { 509 typedef B result_type; 510 B operator()(X, Y, Z); 511}; 512</pre> 513<p> 514 515If a function object does not define a <code class="literal">result_type</code> typedef, 516the method described below (<code class="literal">sig</code> template) 517is attempted to resolve the return type of the 518function object. If a function object defines both <code class="literal">result_type</code> 519and <code class="literal">sig</code>, <code class="literal">result_type</code> takes precedence. 520 521</p> 522</div> 523<div class="simplesect"> 524<div class="titlepage"><div><div><h5 class="title"> 525<a name="id-1.3.21.7.5.8.4"></a>The sig template</h5></div></div></div> 526<p> 527Another mechanism that make BLL aware of the return type(s) of a function object is defining 528member template struct 529<code class="literal">sig<Args></code> with a typedef 530<code class="literal">type</code> that specifies the return type. 531 532Here is a simple example: 533</p> 534<pre class="programlisting"> 535struct A { 536 template <class Args> struct sig { typedef B type; } 537 B operator()(X, Y, Z); 538}; 539</pre> 540<p> 541 542The template argument <code class="literal">Args</code> is a 543<code class="literal">tuple</code> (or more precisely a <code class="literal">cons</code> list) 544type <a class="xref" href="../lambda.html#cit:boost::tuple" title="The Boost Tuple Library">[<abbr class="abbrev">tuple</abbr>]</a>, where the first element 545is the function 546object type itself, and the remaining elements are the types of 547the arguments, with which the function object is being called. 548 549This may seem overly complex compared to defining the <code class="literal">result_type</code> typedef. 550Howver, there are two significant restrictions with using just a simple 551typedef to express the return type: 552</p> 553<div class="orderedlist"><ol class="orderedlist" type="1"> 554<li class="listitem"><p> 555If the function object defines several function call operators, there is no way to specify different result types for them. 556</p></li> 557<li class="listitem"><p> 558If the function call operator is a template, the result type may 559depend on the template parameters. 560Hence, the typedef ought to be a template too, which the C++ language 561does not support. 562</p></li> 563</ol></div> 564<p> 565 566The following code shows an example, where the return type depends on the type 567of one of the arguments, and how that dependency can be expressed with the 568<code class="literal">sig</code> template: 569 570</p> 571<pre class="programlisting"> 572struct A { 573 574 // the return type equals the third argument type: 575 template<class T1, class T2, class T3> 576 T3 operator()(const T1& t1, const T2& t2, const T3& t3) const; 577 578 template <class Args> 579 class sig { 580 // get the third argument type (4th element) 581 typedef typename 582 boost::tuples::element<3, Args>::type T3; 583 public: 584 typedef typename 585 boost::remove_cv<T3>::type type; 586 }; 587}; 588</pre> 589<p> 590 591 592The elements of the <code class="literal">Args</code> tuple are always 593non-reference types. 594 595Moreover, the element types can have a const or volatile qualifier 596(jointly referred to as <span class="emphasis"><em>cv-qualifiers</em></span>), or both. 597This is since the cv-qualifiers in the arguments can affect the return type. 598The reason for including the potentially cv-qualified function object 599type itself into the <code class="literal">Args</code> tuple, is that the function 600object class can contain both const and non-const (or volatile, even 601const volatile) function call operators, and they can each have a different 602return type. 603</p> 604<p> 605The <code class="literal">sig</code> template can be seen as a 606<span class="emphasis"><em>meta-function</em></span> that maps the argument type tuple to 607the result type of the call made with arguments of the types in the tuple. 608 609As the example above demonstrates, the template can end up being somewhat 610complex. 611Typical tasks to be performed are the extraction of the relevant types 612from the tuple, removing cv-qualifiers etc. 613See the Boost type_traits <a class="xref" href="../lambda.html#cit:boost::type_traits" title="The Boost type_traits">[<abbr class="abbrev">type_traits</abbr>]</a> and 614Tuple <a class="xref" href="../lambda.html#cit:boost::type_traits" title="The Boost type_traits">[<abbr class="abbrev">type_traits</abbr>]</a> libraries 615for tools that can aid in these tasks. 616The <code class="literal">sig</code> templates are a refined version of a similar 617mechanism first introduced in the FC++ library 618<a class="xref" href="../lambda.html#cit:fc++" title="The FC++ library: Functional Programming in C++">[<abbr class="abbrev">fc++</abbr>]</a>. 619</p> 620</div> 621</div> 622</div> 623<div class="section"> 624<div class="titlepage"><div><div><h3 class="title"> 625<a name="lambda.overriding_deduced_return_type"></a>Overriding the deduced return type</h3></div></div></div> 626<div class="toc"><dl class="toc"><dt><span class="section"><a href="le_in_details.html#lambda.nullary_functors_and_ret">Nullary lambda functors and ret</a></span></dt></dl></div> 627<p> 628The return type deduction system may not be able to deduce the return types of some user defined operators or bind expressions with class objects. 629 630A special lambda expression type is provided for stating the return type explicitly and overriding the deduction system. 631To state that the return type of the lambda functor defined by the lambda expression <code class="literal">e</code> is <code class="literal">T</code>, you can write: 632 633</p> 634<pre class="programlisting">ret<T>(e);</pre> 635<p> 636 637The effect is that the return type deduction is not performed for the lambda expression <code class="literal">e</code> at all, but instead, <code class="literal">T</code> is used as the return type. 638Obviously <code class="literal">T</code> cannot be an arbitrary type, the true result of the lambda functor must be implicitly convertible to <code class="literal">T</code>. 639For example: 640 641</p> 642<pre class="programlisting"> 643A a; B b; 644C operator+(A, B); 645int operator*(A, B); 646 ... 647ret<D>(_1 + _2)(a, b); // error (C cannot be converted to D) 648ret<C>(_1 + _2)(a, b); // ok 649ret<float>(_1 * _2)(a, b); // ok (int can be converted to float) 650 ... 651struct X { 652 Y operator(int)(); 653}; 654 ... 655X x; int i; 656bind(x, _1)(i); // error, return type cannot be deduced 657ret<Y>(bind(x, _1))(i); // ok 658</pre> 659<p> 660For bind expressions, there is a short-hand notation that can be used instead of <code class="literal">ret</code>. 661The last line could alternatively be written as: 662 663</p> 664<pre class="programlisting">bind<Z>(x, _1)(i);</pre> 665<p> 666This feature is modeled after the Boost Bind library <a class="xref" href="../lambda.html#cit:boost::bind" title="Boost Bind Library">[<abbr class="abbrev">bind</abbr>]</a>. 667 668</p> 669<p>Note that within nested lambda expressions, 670the <code class="literal">ret</code> must be used at each subexpression where 671the deduction would otherwise fail. 672For example: 673</p> 674<pre class="programlisting"> 675A a; B b; 676C operator+(A, B); D operator-(C); 677 ... 678ret<D>( - (_1 + _2))(a, b); // error 679ret<D>( - ret<C>(_1 + _2))(a, b); // ok 680</pre> 681<p> 682</p> 683<p>If you find yourself using <code class="literal">ret</code> repeatedly with the same types, it is worth while extending the return type deduction (see <a class="xref" href="extending.html" title="Extending return type deduction system">the section called “Extending return type deduction system”</a>). 684</p> 685<div class="section"> 686<div class="titlepage"><div><div><h4 class="title"> 687<a name="lambda.nullary_functors_and_ret"></a>Nullary lambda functors and ret</h4></div></div></div> 688<p> 689As stated above, the effect of <code class="literal">ret</code> is to prevent the return type deduction to be performed. 690However, there is an exception. 691Due to the way the C++ template instantiation works, the compiler is always forced to instantiate the return type deduction templates for zero-argument lambda functors. 692This introduces a slight problem with <code class="literal">ret</code>, best described with an example: 693 694</p> 695<pre class="programlisting"> 696struct F { int operator()(int i) const; }; 697F f; 698 ... 699bind(f, _1); // fails, cannot deduce the return type 700ret<int>(bind(f, _1)); // ok 701 ... 702bind(f, 1); // fails, cannot deduce the return type 703ret<int>(bind(f, 1)); // fails as well! 704</pre> 705<p> 706The BLL cannot deduce the return types of the above bind calls, as <code class="literal">F</code> does not define the typedef <code class="literal">result_type</code>. 707One would expect <code class="literal">ret</code> to fix this, but for the nullary lambda functor that results from a bind expression (last line above) this does not work. 708The return type deduction templates are instantiated, even though it would not be necessary and the result is a compilation error. 709</p> 710<p>The solution to this is not to use the <code class="literal">ret</code> function, but rather define the return type as an explicitly specified template parameter in the <code class="literal">bind</code> call: 711</p> 712<pre class="programlisting"> 713bind<int>(f, 1); // ok 714</pre> 715<p> 716 717The lambda functors created with 718<code class="literal">ret<<em class="parameter"><code>T</code></em>>(bind(<em class="parameter"><code>arg-list</code></em>))</code> and 719<code class="literal">bind<<em class="parameter"><code>T</code></em>>(<em class="parameter"><code>arg-list</code></em>)</code> have the exact same functionality — 720apart from the fact that for some nullary lambda functors the former does not work while the latter does. 721</p> 722</div> 723</div> 724<div class="section"> 725<div class="titlepage"><div><div><h3 class="title"> 726<a name="lambda.delaying_constants_and_variables"></a>Delaying constants and variables</h3></div></div></div> 727<p> 728The unary functions <code class="literal">constant</code>, 729<code class="literal">constant_ref</code> and <code class="literal">var</code> turn their argument into a lambda functor, that implements an identity mapping. 730The former two are for constants, the latter for variables. 731The use of these <span class="emphasis"><em>delayed</em></span> constants and variables is sometimes necessary due to the lack of explicit syntax for lambda expressions. 732For example: 733</p> 734<pre class="programlisting"> 735for_each(a.begin(), a.end(), cout << _1 << ' '); 736for_each(a.begin(), a.end(), cout << ' ' << _1); 737</pre> 738<p> 739The first line outputs the elements of <code class="literal">a</code> separated by spaces, while the second line outputs a space followed by the elements of <code class="literal">a</code> without any separators. 740The reason for this is that neither of the operands of 741<code class="literal">cout << ' '</code> is a lambda expression, hence <code class="literal">cout << ' '</code> is evaluated immediately. 742 743To delay the evaluation of <code class="literal">cout << ' '</code>, one of the operands must be explicitly marked as a lambda expression. 744This is accomplished with the <code class="literal">constant</code> function: 745</p> 746<pre class="programlisting"> 747for_each(a.begin(), a.end(), cout << constant(' ') << _1); 748</pre> 749<p> 750 751The call <code class="literal">constant(' ')</code> creates a nullary lambda functor which stores the character constant <code class="literal">' '</code> 752and returns a reference to it when invoked. 753The function <code class="literal">constant_ref</code> is similar, except that it 754stores a constant reference to its argument. 755 756The <code class="literal">constant</code> and <code class="literal">consant_ref</code> are only 757needed when the operator call has side effects, like in the above example. 758</p> 759<p> 760Sometimes we need to delay the evaluation of a variable. 761Suppose we wanted to output the elements of a container in a numbered list: 762 763</p> 764<pre class="programlisting"> 765int index = 0; 766for_each(a.begin(), a.end(), cout << ++index << ':' << _1 << '\n'); 767for_each(a.begin(), a.end(), cout << ++var(index) << ':' << _1 << '\n'); 768</pre> 769<p> 770 771The first <code class="literal">for_each</code> invocation does not do what we want; <code class="literal">index</code> is incremented only once, and its value is written into the output stream only once. 772By using <code class="literal">var</code> to make <code class="literal">index</code> a lambda expression, we get the desired effect. 773 774</p> 775<p> 776In sum, <code class="literal">var(x)</code> creates a nullary lambda functor, 777which stores a reference to the variable <code class="literal">x</code>. 778When the lambda functor is invoked, a reference to <code class="literal">x</code> is returned. 779</p> 780<div class="simplesect"> 781<div class="titlepage"><div><div><h4 class="title"> 782<a name="id-1.3.21.7.7.5"></a>Naming delayed constants and variables</h4></div></div></div> 783<p> 784It is possible to predefine and name a delayed variable or constant outside a lambda expression. 785The templates <code class="literal">var_type</code>, <code class="literal">constant_type</code> 786and <code class="literal">constant_ref_type</code> serve for this purpose. 787They are used as: 788</p> 789<pre class="programlisting"> 790var_type<T>::type delayed_i(var(i)); 791constant_type<T>::type delayed_c(constant(c)); 792</pre> 793<p> 794The first line defines the variable <code class="literal">delayed_i</code> which is a delayed version of the variable <code class="literal">i</code> of type <code class="literal">T</code>. 795Analogously, the second line defines the constant <code class="literal">delayed_c</code> as a delayed version of the constant <code class="literal">c</code>. 796For example: 797 798</p> 799<pre class="programlisting"> 800int i = 0; int j; 801for_each(a.begin(), a.end(), (var(j) = _1, _1 = var(i), var(i) = var(j))); 802</pre> 803<p> 804is equivalent to: 805</p> 806<pre class="programlisting"> 807int i = 0; int j; 808var_type<int>::type vi(var(i)), vj(var(j)); 809for_each(a.begin(), a.end(), (vj = _1, _1 = vi, vi = vj)); 810</pre> 811<p> 812</p> 813<p> 814Here is an example of naming a delayed constant: 815</p> 816<pre class="programlisting"> 817constant_type<char>::type space(constant(' ')); 818for_each(a.begin(),a.end(), cout << space << _1); 819</pre> 820<p> 821</p> 822</div> 823<div class="simplesect"> 824<div class="titlepage"><div><div><h4 class="title"> 825<a name="id-1.3.21.7.7.6"></a>About assignment and subscript operators</h4></div></div></div> 826<p> 827As described in <a class="xref" href="le_in_details.html#lambda.assignment_and_subscript" title="Assignment and subscript operators">the section called “Assignment and subscript operators”</a>, assignment and subscripting operators are always defined as member functions. 828This means, that for expressions of the form 829<code class="literal">x = y</code> or <code class="literal">x[y]</code> to be interpreted as lambda expressions, the left-hand operand <code class="literal">x</code> must be a lambda expression. 830Consequently, it is sometimes necessary to use <code class="literal">var</code> for this purpose. 831We repeat the example from <a class="xref" href="le_in_details.html#lambda.assignment_and_subscript" title="Assignment and subscript operators">the section called “Assignment and subscript operators”</a>: 832 833</p> 834<pre class="programlisting"> 835int i; 836i = _1; // error 837var(i) = _1; // ok 838</pre> 839<p> 840</p> 841<p> 842 843Note that the compound assignment operators <code class="literal">+=</code>, <code class="literal">-=</code> etc. can be defined as non-member functions, and thus they are interpreted as lambda expressions even if only the right-hand operand is a lambda expression. 844Nevertheless, it is perfectly ok to delay the left operand explicitly. 845For example, <code class="literal">i += _1</code> is equivalent to <code class="literal">var(i) += _1</code>. 846</p> 847</div> 848</div> 849<div class="section"> 850<div class="titlepage"><div><div><h3 class="title"> 851<a name="lambda.lambda_expressions_for_control_structures"></a>Lambda expressions for control structures</h3></div></div></div> 852<div class="toc"><dl class="toc"><dt><span class="section"><a href="le_in_details.html#lambda.switch_statement">Switch statement</a></span></dt></dl></div> 853<p> 854BLL defines several functions to create lambda functors that represent control structures. 855They all take lambda functors as parameters and return <code class="literal">void</code>. 856To start with an example, the following code outputs all even elements of some container <code class="literal">a</code>: 857 858</p> 859<pre class="programlisting"> 860for_each(a.begin(), a.end(), 861 if_then(_1 % 2 == 0, cout << _1)); 862</pre> 863<p> 864</p> 865<p> 866The BLL supports the following function templates for control structures: 867 868</p> 869<pre class="programlisting"> 870if_then(condition, then_part) 871if_then_else(condition, then_part, else_part) 872if_then_else_return(condition, then_part, else_part) 873while_loop(condition, body) 874while_loop(condition) // no body case 875do_while_loop(condition, body) 876do_while_loop(condition) // no body case 877for_loop(init, condition, increment, body) 878for_loop(init, condition, increment) // no body case 879switch_statement(...) 880</pre> 881<p> 882 883The return types of all control construct lambda functor is 884<code class="literal">void</code>, except for <code class="literal">if_then_else_return</code>, 885which wraps a call to the conditional operator 886</p> 887<pre class="programlisting"> 888condition ? then_part : else_part 889</pre> 890<p> 891The return type rules for this operator are somewhat complex. 892Basically, if the branches have the same type, this type is the return type. 893If the type of the branches differ, one branch, say of type 894<code class="literal">A</code>, must be convertible to the other branch, 895say of type <code class="literal">B</code>. 896In this situation, the result type is <code class="literal">B</code>. 897Further, if the common type is an lvalue, the return type will be an lvalue 898too. 899</p> 900<p> 901Delayed variables tend to be commonplace in control structure lambda expressions. 902For instance, here we use the <code class="literal">var</code> function to turn the arguments of <code class="literal">for_loop</code> into lambda expressions. 903The effect of the code is to add 1 to each element of a two-dimensional array: 904 905</p> 906<pre class="programlisting"> 907int a[5][10]; int i; 908for_each(a, a+5, 909 for_loop(var(i)=0, var(i)<10, ++var(i), 910 _1[var(i)] += 1)); 911</pre> 912<p> 913 914 915</p> 916<p> 917The BLL supports an alternative syntax for control expressions, suggested 918by Joel de Guzmann. 919By overloading the <code class="literal">operator[]</code> we can 920get a closer resemblance with the built-in control structures: 921 922</p> 923<pre class="programlisting"> 924if_(condition)[then_part] 925if_(condition)[then_part].else_[else_part] 926while_(condition)[body] 927do_[body].while_(condition) 928for_(init, condition, increment)[body] 929</pre> 930<p> 931 932For example, using this syntax the <code class="literal">if_then</code> example above 933can be written as: 934</p> 935<pre class="programlisting"> 936for_each(a.begin(), a.end(), 937 if_(_1 % 2 == 0)[ cout << _1 ]) 938</pre> 939<p> 940 941As more experience is gained, we may end up deprecating one or the other 942of these syntaces. 943 944</p> 945<div class="section"><div class="titlepage"><div><div><h4 class="title"> 946<a name="lambda.switch_statement"></a>Switch statement</h4></div></div></div></div> 947<p> 948The lambda expressions for <code class="literal">switch</code> control structures are more complex since the number of cases may vary. 949The general form of a switch lambda expression is: 950 951</p> 952<pre class="programlisting"> 953switch_statement(<em class="parameter"><code>condition</code></em>, 954 case_statement<<em class="parameter"><code>label</code></em>>(<em class="parameter"><code>lambda expression</code></em>), 955 case_statement<<em class="parameter"><code>label</code></em>>(<em class="parameter"><code>lambda expression</code></em>), 956 ... 957 default_statement(<em class="parameter"><code>lambda expression</code></em>) 958) 959</pre> 960<p> 961 962The <code class="literal"><em class="parameter"><code>condition</code></em></code> argument must be a lambda expression that creates a lambda functor with an integral return type. 963The different cases are created with the <code class="literal">case_statement</code> functions, and the optional default case with the <code class="literal">default_statement</code> function. 964The case labels are given as explicitly specified template arguments to <code class="literal">case_statement</code> functions and 965<code class="literal">break</code> statements are implicitly part of each case. 966For example, <code class="literal">case_statement<1>(a)</code>, where <code class="literal">a</code> is some lambda functor, generates the code: 967 968</p> 969<pre class="programlisting"> 970case 1: 971 <em class="parameter"><code>evaluate lambda functor</code></em> a; 972 break; 973</pre> 974<p> 975The <code class="literal">switch_statement</code> function is specialized for up to 9 case statements. 976 977</p> 978<p> 979As a concrete example, the following code iterates over some container <code class="literal">v</code> and ouptuts <span class="quote">“<span class="quote">zero</span>”</span> for each <code class="literal">0</code>, <span class="quote">“<span class="quote">one</span>”</span> for each <code class="literal">1</code>, and <span class="quote">“<span class="quote">other: <em class="parameter"><code>n</code></em></span>”</span> for any other value <em class="parameter"><code>n</code></em>. 980Note that another lambda expression is sequenced after the <code class="literal">switch_statement</code> to output a line break after each element: 981 982</p> 983<pre class="programlisting"> 984std::for_each(v.begin(), v.end(), 985 ( 986 switch_statement( 987 _1, 988 case_statement<0>(std::cout << constant("zero")), 989 case_statement<1>(std::cout << constant("one")), 990 default_statement(cout << constant("other: ") << _1) 991 ), 992 cout << constant("\n") 993 ) 994); 995</pre> 996<p> 997</p> 998</div> 999<div class="section"> 1000<div class="titlepage"><div><div><h3 class="title"> 1001<a name="lambda.exceptions"></a>Exceptions</h3></div></div></div> 1002<p> 1003The BLL provides lambda functors that throw and catch exceptions. 1004Lambda functors for throwing exceptions are created with the unary function <code class="literal">throw_exception</code>. 1005The argument to this function is the exception to be thrown, or a lambda functor which creates the exception to be thrown. 1006A lambda functor for rethrowing exceptions is created with the nullary <code class="literal">rethrow</code> function. 1007</p> 1008<p> 1009Lambda expressions for handling exceptions are somewhat more complex. 1010The general form of a lambda expression for try catch blocks is as follows: 1011 1012</p> 1013<pre class="programlisting"> 1014try_catch( 1015 <em class="parameter"><code>lambda expression</code></em>, 1016 catch_exception<<em class="parameter"><code>type</code></em>>(<em class="parameter"><code>lambda expression</code></em>), 1017 catch_exception<<em class="parameter"><code>type</code></em>>(<em class="parameter"><code>lambda expression</code></em>), 1018 ... 1019 catch_all(<em class="parameter"><code>lambda expression</code></em>) 1020) 1021</pre> 1022<p> 1023 1024The first lambda expression is the try block. 1025Each <code class="literal">catch_exception</code> defines a catch block where the 1026explicitly specified template argument defines the type of the exception 1027to catch. 1028 1029The lambda expression within the <code class="literal">catch_exception</code> defines 1030the actions to take if the exception is caught. 1031 1032Note that the resulting exception handlers catch the exceptions as 1033references, i.e., <code class="literal">catch_exception<T>(...)</code> 1034results in the catch block: 1035 1036</p> 1037<pre class="programlisting"> 1038catch(T& e) { ... } 1039</pre> 1040<p> 1041 1042The last catch block can alternatively be a call to 1043<code class="literal">catch_exception<<em class="parameter"><code>type</code></em>></code> 1044or to 1045<code class="literal">catch_all</code>, which is the lambda expression equivalent to 1046<code class="literal">catch(...)</code>. 1047 1048</p> 1049<p> 1050 1051The <a class="xref" href="le_in_details.html#ex:exceptions" title="Example 20.1. Throwing and handling exceptions in lambda expressions.">Example 20.1, “Throwing and handling exceptions in lambda expressions.”</a> demonstrates the use of the BLL 1052exception handling tools. 1053The first handler catches exceptions of type <code class="literal">foo_exception</code>. 1054Note the use of <code class="literal">_1</code> placeholder in the body of the handler. 1055</p> 1056<p> 1057The second handler shows how to throw exceptions, and demonstrates the 1058use of the <span class="emphasis"><em>exception placeholder</em></span> <code class="literal">_e</code>. 1059 1060It is a special placeholder, which refers to the caught exception object 1061within the handler body. 1062 1063Here we are handling an exception of type <code class="literal">std::exception</code>, 1064which carries a string explaining the cause of the exception. 1065 1066This explanation can be queried with the zero-argument member 1067function <code class="literal">what</code>. 1068 1069The expression 1070<code class="literal">bind(&std::exception::what, _e)</code> creates the lambda 1071function for making that call. 1072 1073Note that <code class="literal">_e</code> cannot be used outside of an exception handler lambda expression. 1074 1075 1076The last line of the second handler constructs a new exception object and 1077throws that with <code class="literal">throw exception</code>. 1078 1079Constructing and destructing objects within lambda expressions is 1080explained in <a class="xref" href="le_in_details.html#lambda.construction_and_destruction" title="Construction and destruction">the section called “Construction and destruction”</a> 1081</p> 1082<p> 1083Finally, the third handler (<code class="literal">catch_all</code>) demonstrates 1084rethrowing exceptions. 1085</p> 1086<div class="example"> 1087<a name="ex:exceptions"></a><p class="title"><b>Example 20.1. Throwing and handling exceptions in lambda expressions.</b></p> 1088<div class="example-contents"><pre class="programlisting"> 1089for_each( 1090 a.begin(), a.end(), 1091 try_catch( 1092 bind(foo, _1), // foo may throw 1093 catch_exception<foo_exception>( 1094 cout << constant("Caught foo_exception: ") 1095 << "foo was called with argument = " << _1 1096 ), 1097 catch_exception<std::exception>( 1098 cout << constant("Caught std::exception: ") 1099 << bind(&std::exception::what, _e), 1100 throw_exception(bind(constructor<bar_exception>(), _1))) 1101 ), 1102 catch_all( 1103 (cout << constant("Unknown"), rethrow()) 1104 ) 1105 ) 1106); 1107</pre></div> 1108</div> 1109<br class="example-break"> 1110</div> 1111<div class="section"> 1112<div class="titlepage"><div><div><h3 class="title"> 1113<a name="lambda.construction_and_destruction"></a>Construction and destruction</h3></div></div></div> 1114<p> 1115Operators <code class="literal">new</code> and <code class="literal">delete</code> can be 1116overloaded, but their return types are fixed. 1117 1118Particularly, the return types cannot be lambda functors, 1119which prevents them to be overloaded for lambda expressions. 1120 1121It is not possible to take the address of a constructor, 1122hence constructors cannot be used as target functions in bind expressions. 1123 1124The same is true for destructors. 1125 1126As a way around these constraints, BLL defines wrapper classes for 1127<code class="literal">new</code> and <code class="literal">delete</code> calls, 1128as well as for constructors and destructors. 1129 1130Instances of these classes are function objects, that can be used as 1131target functions of bind expressions. 1132 1133For example: 1134 1135</p> 1136<pre class="programlisting"> 1137int* a[10]; 1138for_each(a, a+10, _1 = bind(new_ptr<int>())); 1139for_each(a, a+10, bind(delete_ptr(), _1)); 1140</pre> 1141<p> 1142 1143The <code class="literal">new_ptr<int>()</code> expression creates 1144a function object that calls <code class="literal">new int()</code> when invoked, 1145and wrapping that inside <code class="literal">bind</code> makes it a lambda functor. 1146 1147In the same way, the expression <code class="literal">delete_ptr()</code> creates 1148a function object that invokes <code class="literal">delete</code> on its argument. 1149 1150Note that <code class="literal">new_ptr<<em class="parameter"><code>T</code></em>>()</code> 1151can take arguments as well. 1152 1153They are passed directly to the constructor invocation and thus allow 1154calls to constructors which take arguments. 1155 1156</p> 1157<p> 1158 1159As an example of constructor calls in lambda expressions, 1160the following code reads integers from two containers <code class="literal">x</code> 1161and <code class="literal">y</code>, 1162constructs pairs out of them and inserts them into a third container: 1163 1164</p> 1165<pre class="programlisting"> 1166vector<pair<int, int> > v; 1167transform(x.begin(), x.end(), y.begin(), back_inserter(v), 1168 bind(constructor<pair<int, int> >(), _1, _2)); 1169</pre> 1170<p> 1171 1172<a class="xref" href="le_in_details.html#table:constructor_destructor_fos" title="Table 20.1. Construction and destruction related function objects.">Table 20.1, “Construction and destruction related function objects.”</a> lists all the function 1173objects related to creating and destroying objects, 1174 showing the expression to create and call the function object, 1175and the effect of evaluating that expression. 1176 1177</p> 1178<div class="table"> 1179<a name="table:constructor_destructor_fos"></a><p class="title"><b>Table 20.1. Construction and destruction related function objects.</b></p> 1180<div class="table-contents"><table class="table" summary="Construction and destruction related function objects."> 1181<colgroup> 1182<col> 1183<col> 1184</colgroup> 1185<thead><tr> 1186<th>Function object call</th> 1187<th>Wrapped expression</th> 1188</tr></thead> 1189<tbody> 1190<tr> 1191<td><code class="literal">constructor<T>()(<em class="parameter"><code>arg_list</code></em>)</code></td> 1192<td>T(<em class="parameter"><code>arg_list</code></em>)</td> 1193</tr> 1194<tr> 1195<td><code class="literal">destructor()(a)</code></td> 1196<td> 1197<code class="literal">a.~A()</code>, where <code class="literal">a</code> is of type <code class="literal">A</code> 1198</td> 1199</tr> 1200<tr> 1201<td><code class="literal">destructor()(pa)</code></td> 1202<td> 1203<code class="literal">pa->~A()</code>, where <code class="literal">pa</code> is of type <code class="literal">A*</code> 1204</td> 1205</tr> 1206<tr> 1207<td><code class="literal">new_ptr<T>()(<em class="parameter"><code>arg_list</code></em>)</code></td> 1208<td><code class="literal">new T(<em class="parameter"><code>arg_list</code></em>)</code></td> 1209</tr> 1210<tr> 1211<td><code class="literal">new_array<T>()(sz)</code></td> 1212<td><code class="literal">new T[sz]</code></td> 1213</tr> 1214<tr> 1215<td><code class="literal">delete_ptr()(p)</code></td> 1216<td><code class="literal">delete p</code></td> 1217</tr> 1218<tr> 1219<td><code class="literal">delete_array()(p)</code></td> 1220<td><code class="literal">delete p[]</code></td> 1221</tr> 1222</tbody> 1223</table></div> 1224</div> 1225<br class="table-break"> 1226</div> 1227<div class="section"> 1228<div class="titlepage"><div><div><h3 class="title"> 1229<a name="id-1.3.21.7.11"></a>Special lambda expressions</h3></div></div></div> 1230<div class="toc"><dl class="toc"> 1231<dt><span class="section"><a href="le_in_details.html#id-1.3.21.7.11.2">Preventing argument substitution</a></span></dt> 1232<dt><span class="section"><a href="le_in_details.html#lambda.rvalues_as_actual_arguments">Rvalues as actual arguments to lambda functors</a></span></dt> 1233</dl></div> 1234<div class="section"> 1235<div class="titlepage"><div><div><h4 class="title"> 1236<a name="id-1.3.21.7.11.2"></a>Preventing argument substitution</h4></div></div></div> 1237<div class="toc"><dl class="toc"> 1238<dt><span class="section"><a href="le_in_details.html#lambda.unlambda">Unlambda</a></span></dt> 1239<dt><span class="section"><a href="le_in_details.html#id-1.3.21.7.11.2.5">Protect</a></span></dt> 1240</dl></div> 1241<p> 1242When a lambda functor is called, the default behavior is to substitute 1243the actual arguments for the placeholders within all subexpressions. 1244 1245This section describes the tools to prevent the substitution and 1246evaluation of a subexpression, and explains when these tools should be used. 1247</p> 1248<p> 1249The arguments to a bind expression can be arbitrary lambda expressions, 1250e.g., other bind expressions. 1251 1252For example: 1253 1254</p> 1255<pre class="programlisting"> 1256int foo(int); int bar(int); 1257... 1258int i; 1259bind(foo, bind(bar, _1))(i); 1260</pre> 1261<p> 1262 1263The last line makes the call <code class="literal">foo(bar(i));</code> 1264 1265Note that the first argument in a bind expression, the target function, 1266is no exception, and can thus be a bind expression too. 1267 1268The innermost lambda functor just has to return something that can be used 1269as a target function: another lambda functor, function pointer, 1270pointer to member function etc. 1271 1272For example, in the following code the innermost lambda functor makes 1273a selection between two functions, and returns a pointer to one of them: 1274 1275</p> 1276<pre class="programlisting"> 1277int add(int a, int b) { return a+b; } 1278int mul(int a, int b) { return a*b; } 1279 1280int(*)(int, int) add_or_mul(bool x) { 1281 return x ? add : mul; 1282} 1283 1284bool condition; int i; int j; 1285... 1286bind(bind(&add_or_mul, _1), _2, _3)(condition, i, j); 1287</pre> 1288<p> 1289 1290</p> 1291<div class="section"> 1292<div class="titlepage"><div><div><h5 class="title"> 1293<a name="lambda.unlambda"></a>Unlambda</h5></div></div></div> 1294<p>A nested bind expression may occur inadvertently, 1295if the target function is a variable with a type that depends on a 1296template parameter. 1297 1298Typically the target function could be a formal parameter of a 1299function template. 1300 1301In such a case, the programmer may not know whether the target function is a lambda functor or not. 1302</p> 1303<p>Consider the following function template: 1304 1305</p> 1306<pre class="programlisting"> 1307template<class F> 1308int nested(const F& f) { 1309 int x; 1310 ... 1311 bind(f, _1)(x); 1312 ... 1313} 1314</pre> 1315<p> 1316 1317Somewhere inside the function the formal parameter 1318<code class="literal">f</code> is used as a target function in a bind expression. 1319 1320In order for this <code class="literal">bind</code> call to be valid, 1321<code class="literal">f</code> must be a unary function. 1322 1323Suppose the following two calls to <code class="literal">nested</code> are made: 1324 1325</p> 1326<pre class="programlisting"> 1327int foo(int); 1328int bar(int, int); 1329nested(&foo); 1330nested(bind(bar, 1, _1)); 1331</pre> 1332<p> 1333 1334Both are unary functions, or function objects, with appropriate argument 1335and return types, but the latter will not compile. 1336 1337In the latter call, the bind expression inside <code class="literal">nested</code> 1338will become: 1339 1340</p> 1341<pre class="programlisting"> 1342bind(bind(bar, 1, _1), _1) 1343</pre> 1344<p> 1345 1346When this is invoked with <code class="literal">x</code>, 1347after substituitions we end up trying to call 1348 1349</p> 1350<pre class="programlisting"> 1351bar(1, x)(x) 1352</pre> 1353<p> 1354 1355which is an error. 1356 1357The call to <code class="literal">bar</code> returns int, 1358not a unary function or function object. 1359</p> 1360<p> 1361In the example above, the intent of the bind expression in the 1362<code class="literal">nested</code> function is to treat <code class="literal">f</code> 1363as an ordinary function object, instead of a lambda functor. 1364 1365The BLL provides the function template <code class="literal">unlambda</code> to 1366express this: a lambda functor wrapped inside <code class="literal">unlambda</code> 1367is not a lambda functor anymore, and does not take part into the 1368argument substitution process. 1369 1370Note that for all other argument types <code class="literal">unlambda</code> is 1371an identity operation, except for making non-const objects const. 1372</p> 1373<p> 1374Using <code class="literal">unlambda</code>, the <code class="literal">nested</code> 1375function is written as: 1376 1377</p> 1378<pre class="programlisting"> 1379template<class F> 1380int nested(const F& f) { 1381 int x; 1382 ... 1383 bind(unlambda(f), _1)(x); 1384 ... 1385} 1386</pre> 1387<p> 1388 1389</p> 1390</div> 1391<div class="section"> 1392<div class="titlepage"><div><div><h5 class="title"> 1393<a name="id-1.3.21.7.11.2.5"></a>Protect</h5></div></div></div> 1394<p> 1395The <code class="literal">protect</code> function is related to unlambda. 1396 1397It is also used to prevent the argument substitution taking place, 1398but whereas <code class="literal">unlambda</code> turns a lambda functor into 1399an ordinary function object for good, <code class="literal">protect</code> does 1400this temporarily, for just one evaluation round. 1401 1402For example: 1403 1404</p> 1405<pre class="programlisting"> 1406int x = 1, y = 10; 1407(_1 + protect(_1 + 2))(x)(y); 1408</pre> 1409<p> 1410 1411The first call substitutes <code class="literal">x</code> for the leftmost 1412<code class="literal">_1</code>, and results in another lambda functor 1413<code class="literal">x + (_1 + 2)</code>, which after the call with 1414<code class="literal">y</code> becomes <code class="literal">x + (y + 2)</code>, 1415and thus finally 13. 1416</p> 1417<p> 1418Primary motivation for including <code class="literal">protect</code> into the library, 1419was to allow nested STL algorithm invocations 1420(<a class="xref" href="le_in_details.html#lambda.nested_stl_algorithms" title="Nesting STL algorithm invocations">the section called “Nesting STL algorithm invocations”</a>). 1421</p> 1422</div> 1423</div> 1424<div class="section"> 1425<div class="titlepage"><div><div><h4 class="title"> 1426<a name="lambda.rvalues_as_actual_arguments"></a>Rvalues as actual arguments to lambda functors</h4></div></div></div> 1427<p> 1428Actual arguments to the lambda functors cannot be non-const rvalues. 1429This is due to a deliberate design decision: either we have this restriction, 1430or there can be no side-effects to the actual arguments. 1431 1432There are ways around this limitation. 1433 1434We repeat the example from section 1435<a class="xref" href="using_library.html#lambda.actual_arguments_to_lambda_functors" title="About actual arguments to lambda functors">the section called “About actual arguments to lambda functors”</a> and list the 1436different solutions: 1437 1438</p> 1439<pre class="programlisting"> 1440int i = 1; int j = 2; 1441(_1 + _2)(i, j); // ok 1442(_1 + _2)(1, 2); // error (!) 1443</pre> 1444<p> 1445 1446</p> 1447<div class="orderedlist"><ol class="orderedlist" type="1"> 1448<li class="listitem"><p> 1449If the rvalue is of a class type, the return type of the function that 1450creates the rvalue should be defined as const. 1451Due to an unfortunate language restriction this does not work for 1452built-in types, as built-in rvalues cannot be const qualified. 1453</p></li> 1454<li class="listitem"> 1455<p> 1456If the lambda function call is accessible, the <code class="literal">make_const</code> 1457function can be used to <span class="emphasis"><em>constify</em></span> the rvalue. E.g.: 1458 1459</p> 1460<pre class="programlisting"> 1461(_1 + _2)(make_const(1), make_const(2)); // ok 1462</pre> 1463<p> 1464 1465Commonly the lambda function call site is inside a standard algorithm 1466function template, preventing this solution to be used. 1467 1468</p> 1469</li> 1470<li class="listitem"> 1471<p> 1472If neither of the above is possible, the lambda expression can be wrapped 1473in a <code class="literal">const_parameters</code> function. 1474It creates another type of lambda functor, which takes its arguments as 1475const references. For example: 1476 1477</p> 1478<pre class="programlisting"> 1479const_parameters(_1 + _2)(1, 2); // ok 1480</pre> 1481<p> 1482 1483Note that <code class="literal">const_parameters</code> makes all arguments const. 1484Hence, in the case were one of the arguments is a non-const rvalue, 1485and another argument needs to be passed as a non-const reference, 1486this approach cannot be used. 1487</p> 1488</li> 1489<li class="listitem"> 1490<p>If none of the above is possible, there is still one solution, 1491which unfortunately can break const correctness. 1492 1493The solution is yet another lambda functor wrapper, which we have named 1494<code class="literal">break_const</code> to alert the user of the potential dangers 1495of this function. 1496 1497The <code class="literal">break_const</code> function creates a lambda functor that 1498takes its arguments as const, and casts away constness prior to the call 1499to the original wrapped lambda functor. 1500 1501For example: 1502</p> 1503<pre class="programlisting"> 1504int i; 1505... 1506(_1 += _2)(i, 2); // error, 2 is a non-const rvalue 1507const_parameters(_1 += _2)(i, 2); // error, i becomes const 1508break_const(_1 += _2)(i, 2); // ok, but dangerous 1509</pre> 1510<p> 1511 1512Note, that the results of <code class="literal"> break_const</code> or 1513<code class="literal">const_parameters</code> are not lambda functors, 1514so they cannot be used as subexpressions of lambda expressions. For instance: 1515 1516</p> 1517<pre class="programlisting"> 1518break_const(_1 + _2) + _3; // fails. 1519const_parameters(_1 + _2) + _3; // fails. 1520</pre> 1521<p> 1522 1523However, this kind of code should never be necessary, 1524since calls to sub lambda functors are made inside the BLL, 1525and are not affected by the non-const rvalue problem. 1526</p> 1527</li> 1528</ol></div> 1529<p> 1530 1531</p> 1532</div> 1533</div> 1534<div class="section"> 1535<div class="titlepage"><div><div><h3 class="title"> 1536<a name="id-1.3.21.7.12"></a>Casts, sizeof and typeid</h3></div></div></div> 1537<div class="toc"><dl class="toc"> 1538<dt><span class="section"><a href="le_in_details.html#lambda.cast_expressions"> 1539Cast expressions 1540</a></span></dt> 1541<dt><span class="section"><a href="le_in_details.html#id-1.3.21.7.12.3">Sizeof and typeid</a></span></dt> 1542</dl></div> 1543<div class="section"> 1544<div class="titlepage"><div><div><h4 class="title"> 1545<a name="lambda.cast_expressions"></a> 1546Cast expressions 1547</h4></div></div></div> 1548<p> 1549The BLL defines its counterparts for the four cast expressions 1550<code class="literal">static_cast</code>, <code class="literal">dynamic_cast</code>, 1551<code class="literal">const_cast</code> and <code class="literal">reinterpret_cast</code>. 1552 1553The BLL versions of the cast expressions have the prefix 1554<code class="literal">ll_</code>. 1555 1556The type to cast to is given as an explicitly specified template argument, 1557and the sole argument is the expression from which to perform the cast. 1558 1559If the argument is a lambda functor, the lambda functor is evaluated first. 1560 1561For example, the following code uses <code class="literal">ll_dynamic_cast</code> 1562to count the number of <code class="literal">derived</code> instances in the container 1563<code class="literal">a</code>: 1564 1565</p> 1566<pre class="programlisting"> 1567class base {}; 1568class derived : public base {}; 1569 1570vector<base*> a; 1571... 1572int count = 0; 1573for_each(a.begin(), a.end(), 1574 if_then(ll_dynamic_cast<derived*>(_1), ++var(count))); 1575</pre> 1576<p> 1577</p> 1578</div> 1579<div class="section"> 1580<div class="titlepage"><div><div><h4 class="title"> 1581<a name="id-1.3.21.7.12.3"></a>Sizeof and typeid</h4></div></div></div> 1582<p> 1583The BLL counterparts for these expressions are named 1584<code class="literal">ll_sizeof</code> and <code class="literal">ll_typeid</code>. 1585 1586Both take one argument, which can be a lambda expression. 1587The lambda functor created wraps the <code class="literal">sizeof</code> or 1588<code class="literal">typeid</code> call, and when the lambda functor is called 1589the wrapped operation is performed. 1590 1591For example: 1592 1593</p> 1594<pre class="programlisting"> 1595vector<base*> a; 1596... 1597for_each(a.begin(), a.end(), 1598 cout << bind(&type_info::name, ll_typeid(*_1))); 1599</pre> 1600<p> 1601 1602Here <code class="literal">ll_typeid</code> creates a lambda functor for 1603calling <code class="literal">typeid</code> for each element. 1604 1605The result of a <code class="literal">typeid</code> call is an instance of 1606the <code class="literal">type_info</code> class, and the bind expression creates 1607a lambda functor for calling the <code class="literal">name</code> member 1608function of that class. 1609 1610</p> 1611</div> 1612</div> 1613<div class="section"> 1614<div class="titlepage"><div><div><h3 class="title"> 1615<a name="lambda.nested_stl_algorithms"></a>Nesting STL algorithm invocations</h3></div></div></div> 1616<p> 1617The BLL defines common STL algorithms as function object classes, 1618instances of which can be used as target functions in bind expressions. 1619For example, the following code iterates over the elements of a 1620two-dimensional array, and computes their sum. 1621 1622</p> 1623<pre class="programlisting"> 1624int a[100][200]; 1625int sum = 0; 1626 1627std::for_each(a, a + 100, 1628 bind(ll::for_each(), _1, _1 + 200, protect(sum += _1))); 1629</pre> 1630<p> 1631 1632The BLL versions of the STL algorithms are classes, which define the function call operator (or several overloaded ones) to call the corresponding function templates in the <code class="literal">std</code> namespace. 1633All these structs are placed in the subnamespace <code class="literal">boost::lambda:ll</code>. 1634 1635</p> 1636<p> 1637Note that there is no easy way to express an overloaded member function 1638call in a lambda expression. 1639 1640This limits the usefulness of nested STL algorithms, as for instance 1641the <code class="literal">begin</code> function has more than one overloaded 1642definitions in container templates. 1643 1644In general, something analogous to the pseudo-code below cannot be written: 1645 1646</p> 1647<pre class="programlisting"> 1648std::for_each(a.begin(), a.end(), 1649 bind(ll::for_each(), _1.begin(), _1.end(), protect(sum += _1))); 1650</pre> 1651<p> 1652 1653Some aid for common special cases can be provided though. 1654 1655The BLL defines two helper function object classes, 1656<code class="literal">call_begin</code> and <code class="literal">call_end</code>, 1657which wrap a call to the <code class="literal">begin</code> and, respectively, 1658<code class="literal">end</code> functions of a container, and return the 1659<code class="literal">const_iterator</code> type of the container. 1660 1661With these helper templates, the above code becomes: 1662</p> 1663<pre class="programlisting"> 1664std::for_each(a.begin(), a.end(), 1665 bind(ll::for_each(), 1666 bind(call_begin(), _1), bind(call_end(), _1), 1667 protect(sum += _1))); 1668</pre> 1669<p> 1670 1671</p> 1672</div> 1673</div> 1674<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> 1675<td align="left"></td> 1676<td align="right"><div class="copyright-footer">Copyright © 1999-2004 Jaakko Järvi, Gary Powell<p>Use, modification and distribution is subject to the Boost 1677 Software License, Version 1.0. (See accompanying file 1678 <code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</p> 1679</div></td> 1680</tr></table> 1681<hr> 1682<div class="spirit-nav"> 1683<a accesskey="p" href="using_library.html"><img src="../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../lambda.html"><img src="../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="extending.html"><img src="../../../doc/src/images/next.png" alt="Next"></a> 1684</div> 1685</body> 1686</html> 1687