Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/doc/html/lambda/le_in_details.html @ 35

Last change on this file since 35 was 29, checked in by landauf, 17 years ago

updated boost from 1_33_1 to 1_34_1

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