Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/doc/html/lambda/le_in_details.html @ 25

Last change on this file since 25 was 12, checked in by landauf, 17 years ago

added boost

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