Imported Upstream version 1.57.0
[platform/upstream/boost.git] / libs / lambda / doc / detail / lambda_doc.xml
1 <?xml version="1.0" encoding="ISO-Latin-1"?>
2 <!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN"
3   "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd">
4 <library name="Lambda" dirname="lambda" id="lambda" 
5          last-revision="$Date$" 
6          xmlns:xi="http://www.w3.org/2001/XInclude">
7 <libraryinfo>
8   <author>
9     <firstname>Jaakko</firstname>
10     <surname>Järvi</surname>
11      <email>jarvi at cs tamu edu</email>
12   </author>
13
14   <copyright>
15     <year>1999</year>
16     <year>2000</year>
17     <year>2001</year>
18     <year>2002</year>
19     <year>2003</year>
20     <year>2004</year>
21     <holder>Jaakko Järvi</holder>
22     <holder>Gary Powell</holder>
23   </copyright>
24
25   <legalnotice>
26     <para>Use, modification and distribution is subject to the Boost
27     Software License, Version 1.0. (See accompanying file
28     <filename>LICENSE_1_0.txt</filename> or copy at <ulink
29     url="http://www.boost.org/LICENSE_1_0.txt">http://www.boost.org/LICENSE_1_0.txt</ulink>)</para>
30   </legalnotice>
31
32   <librarypurpose>Define small unnamed function objects at the actual call site, and more</librarypurpose>
33   <librarycategory name="category:higher-order"/>
34 </libraryinfo>
35
36   <!--  -->
37
38   <section id="introduction">
39
40     <title>In a nutshell</title>
41
42     <para>
43
44       The Boost Lambda Library (BLL in the sequel) is a C++ template
45       library, which implements form of <emphasis>lambda abstractions</emphasis> for C++.
46 The term originates from functional programming and lambda calculus, where a lambda abstraction defines an unnamed function.
47       The primary motivation for the BLL is to provide flexible and
48       convenient means to define unnamed function objects for STL algorithms.
49 In explaining what the library is about, a line of code says more than a thousand words; the
50       following line outputs the elements of some STL container
51       <literal>a</literal> separated by spaces:
52
53       <programlisting><![CDATA[for_each(a.begin(), a.end(), std::cout << _1 << ' ');]]></programlisting>
54
55       The expression <literal><![CDATA[std::cout << _1 << ' ']]></literal> defines a unary function object. 
56       The variable <literal>_1</literal> is the parameter of this function, a <emphasis>placeholder</emphasis> for the actual argument. 
57       Within each iteration of <literal>for_each</literal>, the function is
58       called with an element of <literal>a</literal> as the actual argument.
59       This actual argument is substituted for the placeholder, and the <quote>body</quote> of the function is evaluated.
60     </para>
61
62     <para>The essence of BLL is letting you define small unnamed function objects, such as the one above, directly on the call site of an STL algorithm.
63     </para>
64   </section>
65
66   <section id="sect:getting_started">
67     <title>Getting Started</title>
68
69     <section>
70       <title>Installing the library</title>
71       
72
73       <para>
74         The library consists of include files only, hence there is no
75         installation procedure. The <literal>boost</literal> include directory
76         must be on the include path.
77         There are a number of include files that give different functionality:
78
79         <!-- TODO: tarkista vielä riippuvuudet-->
80         <itemizedlist>
81
82           <listitem><para>
83               <filename>lambda/lambda.hpp</filename> defines lambda expressions for different C++
84               operators, see <xref linkend="sect:operator_expressions"/>.
85             </para></listitem>
86
87           <listitem><para>
88               <filename>lambda/bind.hpp</filename> defines <literal>bind</literal> functions for up to 9 arguments, see <xref linkend="sect:bind_expressions"/>.</para></listitem>
89
90
91           <listitem><para>
92               <filename>lambda/if.hpp</filename> defines lambda function equivalents for if statements and the conditional operator, see <xref linkend="sect:lambda_expressions_for_control_structures"/> (includes <filename>lambda.hpp</filename>).
93             </para></listitem>
94
95           <listitem><para>
96               <filename>lambda/loops.hpp</filename> defines lambda function equivalent for looping constructs, see <xref linkend="sect:lambda_expressions_for_control_structures"/>.
97             </para></listitem>
98
99           <listitem><para>
100               <filename>lambda/switch.hpp</filename> defines lambda function equivalent for the switch statement, see <xref linkend="sect:lambda_expressions_for_control_structures"/>.
101             </para></listitem>
102
103           <listitem><para>
104               <filename>lambda/construct.hpp</filename> provides tools for writing lambda expressions with constructor, destructor, new and delete invocations, see <xref linkend="sect:construction_and_destruction"/> (includes <filename>lambda.hpp</filename>).
105             </para></listitem>
106
107           <listitem><para>
108               <filename>lambda/casts.hpp</filename> provides lambda versions of different casts, as well as <literal>sizeof</literal> and <literal>typeid</literal>, see <xref linkend="sect:cast_expressions"/>.
109             </para></listitem>
110
111           <listitem><para>
112               <filename>lambda/exceptions.hpp</filename> gives tools for throwing and catching
113               exceptions within lambda functions, <xref linkend="sect:exceptions"/> (includes
114               <filename>lambda.hpp</filename>).
115             </para></listitem>
116
117           <listitem><para>
118               <filename>lambda/algorithm.hpp</filename> and <filename>lambda/numeric.hpp</filename> (cf. standard <filename>algortihm</filename> and <filename>numeric</filename> headers) allow nested STL algorithm invocations, see <xref linkend="sect:nested_stl_algorithms"/>.
119             </para></listitem>
120
121         </itemizedlist>
122
123         Any other header files in the package are for internal use.
124         Additionally, the library depends on two other Boost Libraries, the
125         <emphasis>Tuple</emphasis> <xref linkend="cit:boost::tuple"/> and the <emphasis>type_traits</emphasis> <xref linkend="cit:boost::type_traits"/> libraries, and on the <filename>boost/ref.hpp</filename> header.
126       </para>
127
128       <para>
129         All definitions are placed in the namespace <literal>boost::lambda</literal> and its subnamespaces.
130       </para>
131
132     </section>
133
134     <section>
135       <title>Conventions used in this document</title>
136
137       <para>In most code examples, we omit the namespace prefixes for names in the <literal moreinfo="none">std</literal> and <literal moreinfo="none">boost::lambda</literal> namespaces.
138 Implicit using declarations
139 <programlisting>
140 using namespace std;
141 using namespace boost::lambda;
142 </programlisting>
143 are assumed to be in effect.
144 </para> 
145
146     </section>
147   </section>
148
149   <section>
150     <title>Introduction</title>
151
152     <section>
153       <title>Motivation</title>
154       <para>The Standard Template Library (STL)
155         <xref role="citation" linkend="cit:stepanov:94"/>, now part of the C++ Standard Library <xref role="citation" linkend="cit:c++:98"/>, is a generic container and algorithm library.
156 Typically STL algorithms operate on container elements via <emphasis>function objects</emphasis>. These function objects are passed as arguments to the algorithms.
157 </para>
158
159 <para>
160 Any C++ construct that can be called with the function call syntax
161 is a function object. 
162 The STL contains predefined function objects for some common cases (such as <literal>plus</literal>, <literal>less</literal> and <literal>not1</literal>). 
163 As an example, one possible implementation for the standard <literal>plus</literal> template is:
164
165 <programlisting>
166 <![CDATA[template <class T>
167 struct plus : public binary_function<T, T, T> {
168   T operator()(const T& i, const T& j) const {
169     return i + j; 
170   }
171 };]]>
172 </programlisting>
173
174 The base class <literal><![CDATA[binary_function<T, T, T>]]></literal> contains typedefs for the argument and return types of the function object, which are needed to make the function object <emphasis>adaptable</emphasis>.
175 </para>
176
177 <para>
178 In addition to the basic function object classes, such as the one above,
179 the STL contains <emphasis>binder</emphasis> templates for creating a unary function object from an adaptable binary function object by fixing one of the arguments to a constant value.
180 For example, instead of having to explicitly write a function object class like:
181
182 <programlisting>
183 <![CDATA[class plus_1 {
184   int _i;
185 public:
186   plus_1(const int& i) : _i(i) {}
187   int operator()(const int& j) { return _i + j; }
188 };]]>
189 </programlisting>
190
191 the equivalent functionality can be achieved with the <literal moreinfo="none">plus</literal> template and one of the binder templates (<literal moreinfo="none">bind1st</literal>).
192 E.g., the following two expressions create function objects with identical functionalities; 
193 when invoked, both return the result of adding <literal moreinfo="none">1</literal> to the argument of the function object:
194
195 <programlisting>
196 <![CDATA[plus_1(1)
197 bind1st(plus<int>(), 1)]]>
198 </programlisting>
199
200 The subexpression <literal><![CDATA[plus<int>()]]></literal> in the latter line is a binary function object which computes the sum of two integers, and <literal>bind1st</literal> invokes this function object partially binding the first argument to <literal>1</literal>.
201 As an example of using the above function object, the following code adds <literal>1</literal> to each element of some container <literal>a</literal> and outputs the results into the standard output stream <literal>cout</literal>.
202
203 <programlisting>
204 <![CDATA[transform(a.begin(), a.end(), ostream_iterator<int>(cout),
205           bind1st(plus<int>(), 1));]]>
206 </programlisting>
207
208 </para>
209
210 <para>
211 To make the binder templates more generally applicable, the STL contains <emphasis>adaptors</emphasis> for making 
212 pointers or references to functions, and pointers to member functions, 
213 adaptable.
214
215 Finally, some STL implementations contain function composition operations as
216 extensions to the standard <xref linkend="cit:sgi:02"/>.
217       </para>
218
219 <para>
220 All these tools aim at one goal: to make it possible to specify 
221 <emphasis>unnamed functions</emphasis> in a call of an STL algorithm, 
222 in other words, to pass code fragments as an argument to a function. 
223
224 However, this goal is attained only partially.
225 The simple example above shows that the definition of unnamed functions 
226 with the standard tools is cumbersome.
227
228 Complex expressions involving functors, adaptors, binders and 
229 function composition operations tend to be difficult to comprehend.
230
231 In addition to this, there are significant restrictions in applying 
232 the standard tools. E.g. the standard binders allow only one argument 
233 of a binary function to be bound; there are no binders for 
234 3-ary, 4-ary etc. functions. 
235 </para>
236
237 <para>
238 The Boost Lambda Library provides solutions for the problems described above:
239
240 <itemizedlist>
241 <listitem>
242 <para>
243 Unnamed functions can be created easily with an intuitive syntax. 
244
245 The above example can be written as:
246
247 <programlisting>
248 <![CDATA[transform(a.begin(), a.end(), ostream_iterator<int>(cout), 
249           1 + _1);]]>
250 </programlisting>
251
252 or even more intuitively:
253
254 <programlisting>
255 <![CDATA[for_each(a.begin(), a.end(), cout << (1 + _1));]]>
256 </programlisting>
257 </para>
258
259 </listitem>
260
261 <listitem>
262 <para>
263 Most of the restrictions in argument binding are removed, 
264 arbitrary arguments of practically any C++ function can be bound.
265 </para>
266 </listitem>
267
268 <listitem>
269 <para>
270 Separate function composition operations are not needed, 
271 as function composition is supported implicitly.
272
273 </para>
274 </listitem>
275
276 </itemizedlist>
277
278 </para>
279
280 </section>
281
282
283
284 <section>
285       <title>Introduction to lambda expressions</title>
286
287       <para>
288         Lambda expression are common in functional programming languages. 
289         Their syntax varies between languages (and between different forms of lambda calculus), but the basic form of a lambda expressions is:
290
291
292 <programlisting>
293 lambda x<subscript>1</subscript> ... x<subscript>n</subscript>.e
294 </programlisting>
295         <!-- $\lambda x_1 \cdots x_n . e$ -->
296
297         A lambda expression defines an unnamed function and consists of:
298         <itemizedlist>
299           <listitem>
300             <para>
301               the parameters of this function: <literal>x<subscript>1</subscript> ... x<subscript>n</subscript></literal>.
302               <!--$x_1 \cdots x_n$-->
303             </para>
304           </listitem>
305           <listitem>
306             <para>the expression e which computes the value of the function in terms of the parameters <literal>x<subscript>1</subscript> ... x<subscript>n</subscript></literal>.
307             </para>
308           </listitem>
309         </itemizedlist>
310
311         A simple example of a lambda expression is 
312 <programlisting>
313 lambda x y.x+y
314 </programlisting>
315 Applying the lambda function means substituting the formal parameters with the actual arguments:
316 <programlisting>
317 (lambda x y.x+y) 2 3 = 2 + 3 = 5 
318 </programlisting>
319
320
321       </para>
322
323 <para>
324 In the C++ version of lambda expressions the <literal>lambda x<subscript>1</subscript> ... x<subscript>n</subscript></literal> part is missing and the formal parameters have predefined names.
325 In the current version of the library, 
326 there are three such predefined formal parameters, 
327 called <emphasis>placeholders</emphasis>: 
328 <literal>_1</literal>, <literal>_2</literal> and <literal>_3</literal>. 
329 They refer to the first, second and third argument of the function defined 
330 by the lambda expression.
331         
332 For example, the C++ version of the definition
333 <programlisting>lambda x y.x+y</programlisting>
334 is 
335 <programlisting>_1 + _2</programlisting>
336 </para>
337
338       <para>
339 Hence, there is no syntactic keyword for C++ lambda expressions. 
340         The use of a placeholder as an operand implies that the operator invocation is a lambda expression.
341         However, this is true only for operator invocations.
342         Lambda expressions containing function calls, control structures, casts etc. require special syntactic constructs. 
343         Most importantly, function calls need to be wrapped inside a <literal>bind</literal> function. 
344
345         As an example, consider the lambda expression:
346
347         <programlisting>lambda x y.foo(x,y)</programlisting>
348
349         Rather than <literal>foo(_1, _2)</literal>, the C++ counterpart for this expression is:
350
351         <programlisting>bind(foo, _1, _2)</programlisting>
352
353         We refer to this type of C++ lambda expressions as <emphasis>bind expressions</emphasis>. 
354       </para>
355
356       <para>A lambda expression defines a C++ function object, hence function application syntax is like calling any other function object, for instance: <literal>(_1 + _2)(i, j)</literal>.
357
358
359       </para>
360
361
362
363 <section id="sect:partial_function_application"> 
364 <title>Partial function application</title>
365
366 <para>
367 A bind expression is in effect a <emphasis>partial function application</emphasis>.
368 In partial function application, some of the arguments of a function are bound to fixed values. 
369           The result is another function, with possibly fewer arguments. 
370           When called with the unbound arguments, this new function invokes the original function with the merged argument list of bound and unbound arguments.
371         </para>
372
373 <!--    <para>The underlying implementation of the BLL unifies the two types of lambda expressions (bind expressions and lambda expressions consisting of operator calls).
374           If operators are regarded as functions, it is easy to see that lambda expressions using operators are partial function applications as well. 
375           E.g. the lambda expression <literal>_1 + 1</literal> can be seen as syntactic sugar for the pseudo code <literal>bind(operator+, _1, 1)</literal>.
376         </para>
377 -->
378
379       </section>
380
381
382
383       <section id="sect:terminology">
384         <title>Terminology</title>
385
386         <para>
387           A lambda expression defines a function. A C++ lambda expression concretely constructs a function object, <emphasis>a functor</emphasis>, when evaluated. We use the name <emphasis>lambda functor</emphasis> to refer to such a function object. 
388           Hence, in the terminology adopted here, the result of evaluating a lambda expression is a lambda functor.
389         </para>
390
391       </section>
392
393     </section>
394
395
396
397   </section>
398
399   <section id = "sect:using_library">
400     <title>Using the library</title>
401
402     <para>
403 The purpose of this section is to introduce the basic functionality of the library.
404 There are quite a lot of exceptions and special cases, but discussion of them is postponed until later sections.
405
406
407     </para>
408
409     <section id = "sect:introductory_examples">
410       <title>Introductory Examples</title>
411
412       <para>
413         In this section we give basic examples of using BLL lambda expressions in STL algorithm invocations. 
414         We start with some simple expressions and work up. 
415         First, we initialize the elements of a container, say, a <literal>list</literal>, to the value <literal>1</literal>:
416
417
418         <programlisting>
419 <![CDATA[list<int> v(10);
420 for_each(v.begin(), v.end(), _1 = 1);]]></programlisting>
421
422         The expression <literal>_1 = 1</literal> creates a lambda functor which assigns the value <literal>1</literal> to every element in <literal>v</literal>.<footnote>
423 <para>
424 Strictly taken, the C++ standard defines <literal>for_each</literal> as a <emphasis>non-modifying sequence operation</emphasis>, and the function object passed to <literal moreinfo="none">for_each</literal> should not modify its argument. 
425 The requirements for the arguments of <literal>for_each</literal> are unnecessary strict, since as long as the iterators are <emphasis>mutable</emphasis>, <literal>for_each</literal> accepts a function object that can have side-effects on their argument.
426 Nevertheless, it is straightforward to provide another function template with the functionality of<literal>std::for_each</literal> but more fine-grained requirements for its arguments.
427 </para>
428 </footnote>
429       </para>
430
431       <para>
432         Next, we create a container of pointers and make them point to the elements in the first container <literal>v</literal>:
433
434         <programlisting>
435 <![CDATA[vector<int*> vp(10); 
436 transform(v.begin(), v.end(), vp.begin(), &_1);]]></programlisting>
437
438 The expression <literal><![CDATA[&_1]]></literal> creates a function object for getting the address of each element in <literal>v</literal>.
439 The addresses get assigned to the corresponding elements in <literal>vp</literal>.
440       </para>
441
442       <para>
443         The next code fragment changes the values in <literal>v</literal>. 
444         For each element, the function <literal>foo</literal> is called. 
445 The original value of the element is passed as an argument to <literal>foo</literal>.
446 The result of <literal>foo</literal> is assigned back to the element:
447
448
449         <programlisting>
450 <![CDATA[int foo(int);
451 for_each(v.begin(), v.end(), _1 = bind(foo, _1));]]></programlisting>
452       </para>
453
454
455       <para>
456         The next step is to sort the elements of <literal>vp</literal>:
457         
458         <programlisting>sort(vp.begin(), vp.end(), *_1 > *_2);</programlisting>
459
460         In this call to <literal>sort</literal>, we are sorting the elements by their contents in descending order. 
461       </para>
462
463       <para>
464         Finally, the following <literal>for_each</literal> call outputs the sorted content of <literal>vp</literal> separated by line breaks:
465
466 <programlisting>
467 <![CDATA[for_each(vp.begin(), vp.end(), cout << *_1 << '\n');]]>
468 </programlisting>
469
470 Note that a normal (non-lambda) expression as subexpression of a lambda expression is evaluated immediately.  
471 This may cause surprises. 
472 For instance, if the previous example is rewritten as
473 <programlisting>
474 <![CDATA[for_each(vp.begin(), vp.end(), cout << '\n' << *_1);]]>
475 </programlisting>
476 the subexpression <literal><![CDATA[cout << '\n']]></literal> is evaluated immediately and the effect is to output a single line break, followed by the elements of <literal>vp</literal>.
477 The BLL provides functions <literal>constant</literal> and <literal>var</literal> to turn constants and, respectively, variables into lambda expressions, and can be used to prevent the immediate evaluation of subexpressions:
478 <programlisting>
479 <![CDATA[for_each(vp.begin(), vp.end(), cout << constant('\n') << *_1);]]>
480 </programlisting>
481 These functions are described more thoroughly in <xref linkend="sect:delaying_constants_and_variables"/>
482
483 </para>
484
485
486
487
488
489     </section>
490
491
492     <section id="sect:parameter_and_return_types">
493       <title>Parameter and return types of lambda functors</title>
494
495       <para>
496         During the invocation of a lambda functor, the actual arguments are substituted for the placeholders. 
497         The placeholders do not dictate the type of these actual arguments.
498         The basic rule is that a lambda function can be called with arguments of any types, as long as the lambda expression with substitutions performed is a valid C++ expression. 
499         As an example, the expression
500         <literal>_1 + _2</literal> creates a binary lambda functor. 
501         It can be called with two objects of any types <literal>A</literal> and <literal>B</literal> for which <literal>operator+(A,B)</literal> is defined (and for which BLL knows the return type of the operator, see below).
502       </para>
503
504       <para>
505         C++ lacks a mechanism to query a type of an expression. 
506         However, this precise mechanism is crucial for the implementation of C++ lambda expressions.
507         Consequently, BLL includes a somewhat complex type deduction system which uses a set of traits classes for deducing the resulting type of lambda functions.
508         It handles expressions where the operands are of built-in types and many of the expressions with operands of standard library types.
509         Many of the user defined types are covered as well, particularly if the user defined operators obey normal conventions in defining the return types. 
510       </para>
511
512       <!-- TODO: move  this forward, and just refer to it. -->
513       <para>
514         There are, however, cases when the return type cannot be deduced. For example, suppose you have defined:
515
516         <programlisting>C operator+(A, B);</programlisting>
517
518         The following lambda function invocation fails, since the return type cannot be deduced:
519
520         <programlisting>A a; B b; (_1 + _2)(a, b);</programlisting>
521       </para>
522
523       <para>
524         There are two alternative solutions to this. 
525         The first is to extend the BLL type deduction system to cover your own types (see <xref linkend="sect:extending_return_type_system"/>). 
526         The second is to use a special lambda expression (<literal>ret</literal>) which defines the return type in place (see <xref linkend = "sect:overriding_deduced_return_type"/>):
527
528         <programlisting><![CDATA[A a; B b; ret<C>(_1 + _2)(a, b);]]></programlisting>
529       </para>
530
531       <para>
532         For bind expressions, the return type can be defined as a template argument of the bind function as well: 
533         <programlisting><![CDATA[bind<int>(foo, _1, _2);]]></programlisting>
534
535 <!--
536         A rare case, where the <literal><![CDATA[ret<type>(bind(...))]]></literal> syntax does not work, but
537         <literal><![CDATA[bind<type>(...)]]></literal> does, is explained in <xref linkend="sect:nullary_functors_and_ret"/>.
538 -->
539       </para>
540     </section>
541
542     <section id="sect:actual_arguments_to_lambda_functors">
543       <title>About actual arguments to lambda functors</title>
544
545       <para><emphasis>This section is no longer (or currently) relevant;
546        acual arguments can be non-const rvalues.
547        The section can, however, become relevant again, if in the future BLL will support
548        lambda functors with higher arities than 3.</emphasis></para>
549
550       <para>A general restriction for the actual arguments is that they cannot be non-const rvalues. 
551         For example:
552
553 <programlisting>
554 int i = 1; int j = 2; 
555 (_1 + _2)(i, j); // ok
556 (_1 + _2)(1, 2); // error (!)
557 </programlisting>
558
559         This restriction is not as bad as it may look. 
560         Since the lambda functors are most often called inside STL-algorithms, 
561         the arguments originate from dereferencing iterators and the dereferencing operators seldom return rvalues.
562         And for the cases where they do, there are workarounds discussed in 
563 <xref linkend="sect:rvalues_as_actual_arguments"/>.
564
565
566       </para>
567
568     </section>
569
570
571 <section id="sect:storing_bound_arguments">
572
573 <title>Storing bound arguments in lambda functions</title>
574       
575 <para>
576
577 By default, temporary const copies of the bound arguments are stored 
578 in the lambda functor.
579
580 This means that the value of a bound argument is fixed at the time of the 
581 creation of the lambda function and remains constant during the lifetime 
582 of the lambda function object.
583 For example:
584 <programlisting>
585 int i = 1;
586 (_1 = 2, _1 + i)(i);
587 </programlisting>
588 The comma operator is overloaded to combine lambda expressions into a sequence;
589 the resulting unary lambda functor first assigns 2 to its argument, 
590 then adds the value of <literal>i</literal> to it.
591 The value of the expression in the last line is 3, not 4. 
592 In other words, the lambda expression that is created is
593 <literal>lambda x.(x = 2, x + 1)</literal> rather than
594 <literal>lambda x.(x = 2, x + i)</literal>.
595       
596 </para>
597
598 <para>
599
600 As said, this is the default behavior for which there are exceptions.
601 The exact rules are as follows:
602
603 <itemizedlist>
604
605 <listitem>
606
607 <para>
608
609 The programmer can control the storing mechanism with <literal>ref</literal> 
610 and <literal>cref</literal> wrappers <xref linkend="cit:boost::ref"/>.
611
612 Wrapping an argument with <literal>ref</literal>, or <literal>cref</literal>, 
613 instructs the library to store the argument as a reference, 
614 or as a reference to const respectively.
615
616 For example, if we rewrite the previous example and wrap the variable 
617 <literal>i</literal> with <literal>ref</literal>, 
618 we are creating the lambda expression <literal>lambda x.(x = 2, x + i)</literal> 
619 and the value of the expression in the last line will be 4:
620
621 <programlisting>
622 i = 1;
623 (_1 = 2, _1 + ref(i))(i);
624 </programlisting>
625
626 Note that <literal>ref</literal> and <literal>cref</literal> are different
627 from <literal>var</literal> and <literal>constant</literal>.
628
629 While the latter ones create lambda functors, the former do not. 
630 For example:
631
632 <programlisting>
633 int i; 
634 var(i) = 1; // ok
635 ref(i) = 1; // not ok, ref(i) is not a lambda functor
636 </programlisting>
637
638 The functions <literal>ref</literal> and <literal>cref</literal> mostly 
639 exist for historical reasons,
640 and <literal>ref</literal> can always
641 be replaced with <literal>var</literal>, and <literal>cref</literal> with
642 <literal>constant_ref</literal>. 
643 See <xref linkend="sect:delaying_constants_and_variables"/> for details.
644 The <literal>ref</literal> and <literal>cref</literal> functions are
645 general purpose utility functions in Boost, and hence defined directly
646 in the <literal moreinfo="none">boost</literal> namespace.
647
648 </para>
649 </listitem>
650           
651 <listitem>
652 <para>
653 Array types cannot be copied, they are thus stored as const reference by default.
654 </para>
655 </listitem>
656
657 <listitem>
658
659 <para> 
660 For some expressions it makes more sense to store the arguments as references. 
661
662 For example, the obvious intention of the lambda expression 
663 <literal>i += _1</literal> is that calls to the lambda functor affect the 
664 value of the variable <literal>i</literal>, 
665 rather than some temporary copy of it. 
666
667 As another example, the streaming operators take their leftmost argument 
668 as non-const references. 
669
670 The exact rules are:
671
672 <itemizedlist>
673 <listitem>
674 <para>The left argument of compound assignment operators (<literal>+=</literal>, <literal>*=</literal>, etc.) are stored as references to non-const.</para>
675 </listitem>
676
677 <listitem>
678 <para>If the left argument of <literal><![CDATA[<<]]></literal> or <literal><![CDATA[>>]]></literal>  operator is derived from an instantiation of <literal>basic_ostream</literal> or respectively from <literal>basic_istream</literal>, the argument is stored as a reference to non-const. 
679 For all other types, the argument is stored as a copy.
680 </para>
681 </listitem>
682
683 <listitem>
684 <para>
685 In pointer arithmetic expressions, non-const array types are stored as non-const references.
686 This is to prevent pointer arithmetic making non-const arrays const. 
687
688 </para>
689 </listitem> 
690
691 </itemizedlist>
692
693 </para>
694 </listitem>
695
696 </itemizedlist>
697 </para>
698
699 </section>
700
701 </section>
702
703 <section id="sect:lambda_expressions_in_details">
704 <title>Lambda expressions in details</title>
705
706 <para>
707 This section describes different categories of lambda expressions in details.
708 We devote a separate section for each of the possible forms of a lambda expression.
709
710
711 </para>
712
713 <section id="sect:placeholders">
714 <title>Placeholders</title>
715
716 <para>
717 The BLL defines three placeholder types: <literal>placeholder1_type</literal>, <literal>placeholder2_type</literal> and <literal>placeholder3_type</literal>. 
718 BLL has a predefined placeholder variable for each placeholder type: <literal>_1</literal>, <literal>_2</literal> and <literal>_3</literal>. 
719 However, the user is not forced to use these placeholders. 
720 It is easy to define placeholders with alternative names.
721 This is done by defining new variables of placeholder types. 
722 For example:
723
724 <programlisting>boost::lambda::placeholder1_type X;
725 boost::lambda::placeholder2_type Y;
726 boost::lambda::placeholder3_type Z;
727 </programlisting>
728
729 With these variables defined, <literal>X += Y * Z</literal> is equivalent to <literal>_1 += _2 * _3</literal>.
730 </para>
731
732 <para>
733 The use of placeholders in the lambda expression determines whether the resulting function is nullary, unary, binary or 3-ary. 
734 The highest placeholder index is decisive. For example:
735
736 <programlisting>
737 _1 + 5              // unary
738 _1 * _1 + _1        // unary
739 _1 + _2             // binary
740 bind(f, _1, _2, _3) // 3-ary
741 _3 + 10             // 3-ary
742 </programlisting>
743
744 Note that the last line creates a 3-ary function, which adds <literal>10</literal> to its <emphasis>third</emphasis> argument. 
745 The first two arguments are discarded.
746 Furthermore, lambda functors only have a minimum arity.
747 One can always provide more arguments (up the number of supported placeholders)
748 that is really needed.
749 The remaining arguments are just discarded.
750 For example:
751
752 <programlisting>
753 int i, j, k; 
754 _1(i, j, k)        // returns i, discards j and k
755 (_2 + _2)(i, j, k) // returns j+j, discards i and k
756 </programlisting>
757
758 See
759 <xref linkend="sect:why_weak_arity"/> for the design rationale behind this
760 functionality.
761
762 </para>
763
764 <para>
765 In addition to these three placeholder types, there is also a fourth placeholder type <literal>placeholderE_type</literal>.
766 The use of this placeholder is defined in <xref linkend="sect:exceptions"/> describing exception handling in lambda expressions. 
767 </para>
768
769 <para>When an actual argument is supplied for a placeholder, the parameter passing mode is always by reference. 
770 This means that any side-effects to the placeholder are reflected to the actual argument. 
771 For example:
772
773
774 <programlisting>
775 <![CDATA[int i = 1; 
776 (_1 += 2)(i);         // i is now 3
777 (++_1, cout << _1)(i) // i is now 4, outputs 4]]>
778 </programlisting>
779 </para>
780
781 </section>
782
783 <section id="sect:operator_expressions">
784 <title>Operator expressions</title>
785
786 <para>
787 The basic rule is that any C++ operator invocation with at least one argument being a lambda expression is itself a lambda expression.
788 Almost all overloadable operators are supported. 
789 For example, the following is a valid lambda expression:
790
791 <programlisting><![CDATA[cout << _1, _2[_3] = _1 && false]]></programlisting>
792 </para>
793
794 <para>
795 However, there are some restrictions that originate from the C++ operator overloading rules, and some special cases.
796 </para>
797
798
799 <section>
800 <title>Operators that cannot be overloaded</title>
801
802 <para>
803 Some operators cannot be overloaded at all (<literal>::</literal>, <literal>.</literal>, <literal>.*</literal>).
804 For some operators, the requirements on return types prevent them to be overloaded to create lambda functors.
805 These operators are <literal>->.</literal>, <literal>-></literal>, <literal>new</literal>, <literal>new[]</literal>, <literal>delete</literal>, <literal>delete[]</literal> and <literal>?:</literal> (the conditional operator).
806 </para>
807
808 </section>
809
810 <section id="sect:assignment_and_subscript">
811 <title>Assignment and subscript operators</title>
812
813 <para>
814 These operators must be implemented as class members. 
815 Consequently, the left operand must be a lambda expression. For example:
816
817 <programlisting>
818 int i; 
819 _1 = i;      // ok
820 i = _1;      // not ok. i is not a lambda expression
821 </programlisting>
822
823 There is a simple solution around this limitation, described in <xref linkend="sect:delaying_constants_and_variables"/>.
824 In short, 
825 the left hand argument can be explicitly turned into a lambda functor by wrapping it with a special <literal>var</literal> function:
826 <programlisting>
827 var(i) = _1; // ok
828 </programlisting>
829
830 </para>
831 </section>
832
833 <section id="sect:logical_operators">
834 <title>Logical operators</title>
835
836 <para>
837 Logical operators obey the short-circuiting evaluation rules. For example, in the following code, <literal>i</literal> is never incremented:
838 <programlisting>
839 bool flag = true; int i = 0;
840 (_1 || ++_2)(flag, i);
841 </programlisting>
842 </para>
843 </section>
844
845 <section id="sect:comma_operator">
846 <title>Comma operator</title>
847
848 <para>
849 Comma operator is the <quote>statement separator</quote> in lambda expressions. 
850 Since comma is also the separator between arguments in a function call, extra parenthesis are sometimes needed:
851
852 <programlisting>
853 for_each(a.begin(), a.end(), (++_1, cout &lt;&lt; _1));
854 </programlisting>
855
856 Without the extra parenthesis around <literal>++_1, cout &lt;&lt; _1</literal>, the code would be interpreted as an attempt to call <literal>for_each</literal> with four arguments.
857 </para>
858 <para>
859 The lambda functor created by the comma operator adheres to the C++ rule of always evaluating the left operand before the right one.
860 In the above example, each element of <literal>a</literal> is first incremented, then written to the stream.
861 </para>
862 </section>
863
864 <section id="sect:function_call_operator">
865 <title>Function call operator</title>
866
867 <para>
868 The function call operators have the effect of evaluating the lambda
869 functor. 
870 Calls with too few arguments lead to a compile time error.
871 </para>
872 </section>
873
874 <section id="sect:member_pointer_operator">
875 <title>Member pointer operator</title>
876
877 <para>
878 The member pointer operator <literal>operator->*</literal> can be overloaded freely. 
879 Hence, for user defined types, member pointer operator is no special case.
880 The built-in meaning, however, is a somewhat more complicated case.
881 The built-in member pointer operator is applied if the left argument is a pointer to an object of some class <literal>A</literal>, and the right hand argument is a pointer to a member of <literal>A</literal>, or a pointer to a member of a class from which <literal>A</literal> derives.
882 We must separate two cases:
883
884 <itemizedlist>
885
886 <listitem>
887 <para>The right hand argument is a pointer to a data member. 
888 In 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. 
889 For example:
890 <programlisting>
891 <![CDATA[struct A { int d; };
892 A* a = new A();
893   ...
894 (a ->* &A::d);     // returns a reference to a->d 
895 (_1 ->* &A::d)(a); // likewise]]>
896 </programlisting>
897 </para>
898 </listitem>
899
900 <listitem>
901 <para>
902 The right hand argument is a pointer to a member function.
903 For a built-in call like this, the result is kind of a delayed member function call. 
904 Such an expression must be followed by a function argument list, with which the delayed member function call is performed.
905 For example:
906 <programlisting>
907 <![CDATA[struct B { int foo(int); };
908 B* b = new B();
909   ...
910 (b ->* &B::foo)         // returns a delayed call to b->foo
911                         // a function argument list must follow
912 (b ->* &B::foo)(1)      // ok, calls b->foo(1)
913
914 (_1 ->* &B::foo)(b);    // returns a delayed call to b->foo, 
915                         // no effect as such
916 (_1 ->* &B::foo)(b)(1); // calls b->foo(1)]]>
917 </programlisting>
918 </para>
919 </listitem>
920 </itemizedlist>
921 </para>
922 </section>
923
924 </section>
925
926 <section id="sect:bind_expressions">
927 <title>Bind expressions</title>
928
929 <para>
930 Bind expressions can have two forms: 
931
932 <!-- TODO: shouldn't really be emphasis, but a variable or something-->
933 <programlisting>
934 bind(<parameter>target-function</parameter>, <parameter>bind-argument-list</parameter>)
935 bind(<parameter>target-member-function</parameter>, <parameter>object-argument</parameter>, <parameter>bind-argument-list</parameter>)
936 </programlisting>
937
938 A bind expression delays the call of a function. 
939 If this <emphasis>target function</emphasis> is <emphasis>n</emphasis>-ary, then the <literal><emphasis>bind-argument-list</emphasis></literal> must contain <emphasis>n</emphasis> arguments as well.
940 In the current version of the BLL, <inlineequation>0 &lt;= n &lt;= 9</inlineequation> must hold. 
941 For member functions, the number of arguments must be at most <inlineequation>8</inlineequation>, as the object argument takes one argument position.
942
943 Basically, the
944 <emphasis><literal>bind-argument-list</literal></emphasis> 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. 
945 Note that also the target function can be a lambda expression.
946
947 The result of a bind expression is either a nullary, unary, binary or 3-ary function object depending on the use of placeholders in the <emphasis><literal>bind-argument-list</literal></emphasis> (see <xref linkend="sect:placeholders"/>).
948 </para>
949
950 <para>
951 The 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:
952 <programlisting>
953 bind&lt;<emphasis>RET</emphasis>&gt;(<emphasis>target-function</emphasis>, <emphasis>bind-argument-list</emphasis>)
954 </programlisting>
955 This is only necessary if the return type of the target function cannot be deduced.
956 </para>
957
958 <para>
959 The following sections describe the different types of bind expressions.
960 </para>
961
962 <section id="sect:function_pointers_as_targets">
963 <title>Function pointers or references as targets</title>
964
965 <para>The target function can be a pointer or a reference to a function and it can be either bound or unbound. For example:
966 <programlisting>
967 <![CDATA[X foo(A, B, C); A a; B b; C c;
968 bind(foo, _1, _2, c)(a, b);
969 bind(&foo, _1, _2, c)(a, b);
970 bind(_1, a, b, c)(foo);]]>
971 </programlisting>
972  
973 The return type deduction always succeeds with this type of bind expressions. 
974 </para>
975
976 <para>
977 Note, 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.
978 This means that overloaded functions cannot be used in bind expressions directly, e.g.:
979 <programlisting>
980 <![CDATA[void foo(int);
981 void foo(float);
982 int i; 
983   ...
984 bind(&foo, _1)(i);                            // error 
985   ...
986 void (*pf1)(int) = &foo;
987 bind(pf1, _1)(i);                             // ok
988 bind(static_cast<void(*)(int)>(&foo), _1)(i); // ok]]>
989 </programlisting>
990 </para>
991 </section>
992
993 <section id="member_functions_as_targets">
994 <title>Member functions as targets</title>
995
996 <para>
997 The syntax for using pointers to member function in bind expression is:
998 <programlisting>
999 bind(<parameter>target-member-function</parameter>, <parameter>object-argument</parameter>, <parameter>bind-argument-list</parameter>)
1000 </programlisting>
1001
1002 The object argument can be a reference or pointer to the object, the BLL supports both cases with a uniform interface: 
1003
1004 <programlisting>
1005 <![CDATA[bool A::foo(int) const; 
1006 A a;
1007 vector<int> ints; 
1008   ...
1009 find_if(ints.begin(), ints.end(), bind(&A::foo, a, _1)); 
1010 find_if(ints.begin(), ints.end(), bind(&A::foo, &a, _1));]]>
1011 </programlisting>
1012
1013 Similarly, if the object argument is unbound, the resulting lambda functor can be called both via a pointer or a reference:
1014
1015 <programlisting>
1016 <![CDATA[bool A::foo(int); 
1017 list<A> refs; 
1018 list<A*> pointers; 
1019   ...
1020 find_if(refs.begin(), refs.end(), bind(&A::foo, _1, 1)); 
1021 find_if(pointers.begin(), pointers.end(), bind(&A::foo, _1, 1));]]>
1022 </programlisting>
1023
1024 </para>
1025
1026 <!--%The exact rules for the object argument (whether it is bound, or supplied in the lambda function invoction) are as follows:
1027 %If the target function is a pointer to a member function of some class \snip{A}, then the object argument must be an expression of type \snip{B}, where either
1028 %\begin{itemize}
1029 %\item \snip{B} = \snip{A} or there is an implicit conversion from \snip{B} to \snip{A}.
1030 %\item \snip{B} = \snip{A*}.
1031 %\item \snip{B} = \snip{C*}, where \snip{C} is any class derived form \snip{A}.
1032 %\end{itemize}
1033 %For example:
1034 %\begin{alltt}
1035 %struct A \{
1036 %  virtual void f();
1037 %  void fc() const;
1038 %\};
1039 %
1040 %struct B : public A \{ 
1041 %  virtual void f(); 
1042 %\};
1043 %
1044 %struct C \{
1045 %  operator A const() \{ return A(); \}
1046 %\};
1047 %
1048 % A a; B b; C c;
1049 %  ...
1050 % bind(&A::f, a)(); 
1051 % bind(&A::f, b)(); // calls B::f
1052 % bind(&A::fc, c)(); 
1053 %
1054 % bind(&A::f, &a)();
1055 % bind(&A::f, &b)(); // calls B::f
1056 % bind(&A::f, &c)(); // error: no conversion from C* \(\rightarrow\) A, 
1057 %\end{alltt}
1058 -->
1059
1060 <para>
1061 Even though the interfaces are the same, there are important semantic differences between using a pointer or a reference as the object argument.
1062 The differences stem from the way <literal>bind</literal>-functions take their parameters, and how the bound parameters are stored within the lambda functor.
1063 The object argument has the same parameter passing and storing mechanism as any other bind argument slot (see <xref linkend="sect:storing_bound_arguments"/>); it is passed as a const reference and stored as a const copy in the lambda functor.
1064 This creates some asymmetry between the lambda functor and the original member function, and between seemingly similar lambda functors. For example:
1065 <programlisting>
1066 class A {
1067   int i; mutable int j;
1068 public:
1069
1070   A(int ii, int jj) : i(ii), j(jj) {};
1071   void set_i(int x) { i = x; }; 
1072   void set_j(int x) const { j = x; }; 
1073 };
1074 </programlisting>
1075
1076 When a pointer is used, the behavior is what the programmer might expect:
1077
1078 <programlisting>
1079 <![CDATA[A a(0,0); int k = 1;
1080 bind(&A::set_i, &a, _1)(k); // a.i == 1
1081 bind(&A::set_j, &a, _1)(k); // a.j == 1]]>
1082 </programlisting>
1083
1084 Even though a const copy of the object argument is stored, the original object <literal>a</literal> is still modified.
1085 This is since the object argument is a pointer, and the pointer is copied, not the object it points to.
1086 When we use a reference, the behaviour is different:
1087
1088 <programlisting>
1089 <![CDATA[A a(0,0); int k = 1;
1090 bind(&A::set_i, a, _1)(k); // error; a const copy of a is stored. 
1091                            // Cannot call a non-const function set_i
1092 bind(&A::set_j, a, _1)(k); // a.j == 0, as a copy of a is modified]]>
1093 </programlisting>
1094 </para>
1095
1096 <para>
1097 To prevent the copying from taking place, one can use the <literal>ref</literal> or <literal>cref</literal> wrappers (<literal>var</literal> and <literal>constant_ref</literal> would do as well):
1098 <programlisting>
1099 <![CDATA[bind(&A::set_i, ref(a), _1)(k); // a.j == 1
1100 bind(&A::set_j, cref(a), _1)(k); // a.j == 1]]>
1101 </programlisting>
1102 </para>
1103
1104 <para>Note that the preceding discussion is relevant only for bound arguments. 
1105 If the object argument is unbound, the parameter passing mode is always by reference. 
1106 Hence, the argument <literal>a</literal> is not copied in the calls to the two lambda functors below:
1107 <programlisting>
1108 <![CDATA[A a(0,0);
1109 bind(&A::set_i, _1, 1)(a); // a.i == 1
1110 bind(&A::set_j, _1, 1)(a); // a.j == 1]]>
1111 </programlisting>
1112 </para>
1113 </section>
1114
1115 <section id="sect:members_variables_as_targets">
1116 <title>Member variables as targets</title>
1117
1118 <para>
1119 A pointer to a member variable is not really a function, but 
1120 the first argument to the <literal>bind</literal> function can nevertheless
1121 be a pointer to a member variable.
1122 Invoking such a bind expression returns a reference to the data member.
1123 For example:
1124
1125 <programlisting>
1126 <![CDATA[struct A { int data; };
1127 A a;
1128 bind(&A::data, _1)(a) = 1;     // a.data == 1]]>
1129 </programlisting>
1130
1131 The cv-qualifiers of the object whose member is accessed are respected.
1132 For example, the following tries to write into a const location:
1133 <programlisting>
1134 <![CDATA[const A ca = a;
1135 bind(&A::data, _1)(ca) = 1;     // error]]>
1136 </programlisting>
1137
1138 </para>
1139 </section>
1140
1141 <section id="sect:function_objects_as_targets">
1142 <title>Function objects as targets</title>
1143
1144 <para>
1145
1146 Function objects, that is, class objects which have the function call 
1147 operator defined, can be used as target functions. 
1148
1149 In general, BLL cannot deduce the return type of an arbitrary function object. 
1150
1151 However, there are two methods for giving BLL this capability for a certain 
1152 function object class.
1153
1154 </para>
1155
1156 <simplesect>
1157
1158 <title>The result_type typedef</title>
1159
1160 <para>
1161
1162 The BLL supports the standard library convention of declaring the return type
1163 of a function object with a member typedef named <literal>result_type</literal> in the
1164 function object class.
1165
1166 Here is a simple example:
1167 <programlisting>
1168 <![CDATA[struct A {
1169   typedef B result_type;
1170   B operator()(X, Y, Z); 
1171 };]]>
1172 </programlisting>
1173
1174 If a function object does not define a <literal>result_type</literal> typedef, 
1175 the method described below (<literal>sig</literal> template) 
1176 is attempted to resolve the return type of the
1177 function object. If a function object defines both <literal>result_type</literal>
1178 and <literal>sig</literal>, <literal>result_type</literal> takes precedence.
1179
1180 </para>
1181
1182 </simplesect>
1183
1184 <simplesect>
1185
1186 <title>The sig template</title>
1187
1188 <para>
1189 Another mechanism that make BLL aware of the return type(s) of a function object is defining
1190 member template struct 
1191 <literal><![CDATA[sig<Args>]]></literal> with a typedef 
1192 <literal>type</literal> that specifies the return type.
1193
1194 Here is a simple example:
1195 <programlisting>
1196 <![CDATA[struct A {
1197   template <class Args> struct sig { typedef B type; }
1198   B operator()(X, Y, Z); 
1199 };]]>
1200 </programlisting>
1201
1202 The template argument <literal>Args</literal> is a 
1203 <literal>tuple</literal> (or more precisely a <literal>cons</literal> list) 
1204 type <xref linkend="cit:boost::tuple"/>, where the first element 
1205 is the function 
1206 object type itself, and the remaining elements are the types of 
1207 the arguments, with which the function object is being called.
1208
1209 This may seem overly complex compared to defining the <literal>result_type</literal> typedef.
1210 Howver, there are two significant restrictions with using just a simple
1211 typedef to express the return type:
1212 <orderedlist>
1213 <listitem>
1214 <para>
1215 If the function object defines several function call operators, there is no way to specify different result types for them.
1216 </para>
1217 </listitem>
1218 <listitem>
1219 <para>
1220 If the function call operator is a template, the result type may 
1221 depend on the template parameters. 
1222 Hence, the typedef ought to be a template too, which the C++ language 
1223 does not support.
1224 </para>
1225 </listitem>
1226 </orderedlist>
1227
1228 The following code shows an example, where the return type depends on the type
1229 of one of the arguments, and how that dependency can be expressed with the
1230 <literal>sig</literal> template:
1231
1232 <programlisting>
1233 <![CDATA[struct A {
1234
1235   // the return type equals the third argument type:
1236   template<class T1, T2, T3>
1237   T3 operator()(const T1& t1, const T2& t2, const T3& t3);
1238
1239   template <class Args> 
1240   class sig {
1241     // get the third argument type (4th element)
1242     typedef typename 
1243       boost::tuples::element<3, Args>::type T3;
1244   public:
1245     typedef typename 
1246       boost::remove_cv<T3>::type type;
1247   }
1248 };]]>
1249 </programlisting>
1250
1251
1252 The elements of the <literal>Args</literal> tuple are always 
1253 non-reference types.
1254
1255 Moreover, the element types can have a const or volatile qualifier
1256 (jointly referred to as <emphasis>cv-qualifiers</emphasis>), or both.
1257 This is since the cv-qualifiers in the arguments can affect the return type.
1258 The reason for including the potentially cv-qualified function object 
1259 type itself into the <literal>Args</literal> tuple, is that the function
1260 object class can contain both const and non-const (or volatile, even
1261 const volatile) function call operators, and they can each have a different
1262 return type.
1263 </para>
1264
1265 <para>
1266 The <literal>sig</literal> template can be seen as a 
1267 <emphasis>meta-function</emphasis> that maps the argument type tuple to 
1268 the result type of the call made with arguments of the types in the tuple.
1269
1270 As the example above demonstrates, the template can end up being somewhat 
1271 complex.
1272 Typical tasks to be performed are the extraction of the relevant types 
1273 from the tuple, removing cv-qualifiers etc.
1274 See the Boost type_traits <xref linkend="cit:boost::type_traits"/> and
1275 Tuple <xref linkend="cit:boost::type_traits"/> libraries 
1276 for tools that can aid in these tasks.
1277 The <literal>sig</literal> templates are a refined version of a similar
1278 mechanism first introduced in the FC++ library  
1279 <xref linkend="cit:fc++"/>.
1280 </para>
1281
1282 </simplesect>
1283
1284 </section>
1285
1286
1287
1288 </section>
1289
1290 <section id="sect:overriding_deduced_return_type">
1291 <title>Overriding the deduced return type</title>
1292
1293 <para>
1294 The return type deduction system may not be able to deduce the return types of some user defined operators or bind expressions with class objects.
1295 <!-- (see the example in <xref linkend="sect:parameter_and_return_types"/>).-->
1296 A special lambda expression type is provided for stating the return type explicitly and overriding the deduction system. 
1297 To state that the return type of the lambda functor defined by the lambda expression <literal>e</literal> is <literal>T</literal>, you can write:
1298
1299 <programlisting><![CDATA[ret<T>(e);]]></programlisting>
1300
1301 The effect is that the return type deduction is not performed for the lambda expression <literal>e</literal> at all, but instead, <literal>T</literal> is used as the return type. 
1302 Obviously <literal>T</literal> cannot be an arbitrary type, the true result of the lambda functor must be implicitly convertible to <literal>T</literal>. 
1303 For example:
1304
1305 <programlisting>
1306 <![CDATA[A a; B b;
1307 C operator+(A, B);
1308 int operator*(A, B); 
1309   ...
1310 ret<D>(_1 + _2)(a, b);     // error (C cannot be converted to D)
1311 ret<C>(_1 + _2)(a, b);     // ok
1312 ret<float>(_1 * _2)(a, b); // ok (int can be converted to float)
1313   ...
1314 struct X {
1315   Y operator(int)();   
1316 };
1317   ...
1318 X x; int i;
1319 bind(x, _1)(i);            // error, return type cannot be deduced
1320 ret<Y>(bind(x, _1))(i);    // ok]]>
1321 </programlisting>
1322 For bind expressions, there is a short-hand notation that can be used instead of <literal>ret</literal>. 
1323 The last line could alternatively be written as:
1324
1325 <programlisting><![CDATA[bind<Z>(x, _1)(i);]]></programlisting>
1326 This feature is modeled after the Boost Bind library <xref linkend="cit:boost::bind"/>.
1327
1328 </para>
1329
1330 <para>Note that within nested lambda expressions, 
1331 the <literal>ret</literal> must be used at each subexpression where 
1332 the deduction would otherwise fail. 
1333 For example:
1334 <programlisting>
1335 <![CDATA[A a; B b;
1336 C operator+(A, B); D operator-(C);
1337   ...
1338 ret<D>( - (_1 + _2))(a, b); // error 
1339 ret<D>( - ret<C>(_1 + _2))(a, b); // ok]]>
1340 </programlisting>
1341 </para>
1342
1343 <para>If you find yourself using  <literal>ret</literal> repeatedly with the same types, it is worth while extending the return type deduction (see <xref linkend="sect:extending_return_type_system"/>).
1344 </para>
1345
1346 <section id="sect:nullary_functors_and_ret">
1347 <title>Nullary lambda functors and ret</title>
1348
1349 <para>
1350 As stated above, the effect of <literal>ret</literal> is to prevent the return type deduction to be performed. 
1351 However, there is an exception. 
1352 Due 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.
1353 This introduces a slight problem with <literal>ret</literal>, best described with an example:
1354
1355 <programlisting>
1356 <![CDATA[struct F { int operator()(int i) const; }; 
1357 F f;
1358   ...
1359 bind(f, _1);           // fails, cannot deduce the return type
1360 ret<int>(bind(f, _1)); // ok
1361   ...
1362 bind(f, 1);            // fails, cannot deduce the return type
1363 ret<int>(bind(f, 1));  // fails as well!]]>
1364 </programlisting>
1365 The BLL cannot deduce the return types of the above bind calls, as <literal>F</literal> does not define the typedef <literal>result_type</literal>. 
1366 One would expect <literal>ret</literal> to fix this, but for the nullary lambda functor that results from a bind expression (last line above) this does not work.
1367 The return type deduction templates are instantiated, even though it would not be necessary and the result is a compilation error.
1368 </para>
1369
1370 <para>The solution to this is not to use the <literal>ret</literal> function, but rather define the return type as an explicitly specified template parameter in the <literal>bind</literal> call:
1371 <programlisting>
1372 <![CDATA[bind<int>(f, 1);       // ok]]>
1373 </programlisting>
1374
1375 The lambda functors created with 
1376 <literal>ret&lt;<parameter>T</parameter>&gt;(bind(<parameter>arg-list</parameter>))</literal> and 
1377 <literal>bind&lt;<parameter>T</parameter>&gt;(<parameter>arg-list</parameter>)</literal> have the exact same functionality &mdash;
1378 apart from the fact that for some nullary lambda functors the former does not work while the latter does. 
1379 </para>
1380 </section>
1381 </section>
1382
1383
1384 <section id="sect:delaying_constants_and_variables">
1385 <title>Delaying constants and variables</title>
1386
1387 <para>
1388 The unary functions <literal>constant</literal>,
1389 <literal>constant_ref</literal> and <literal>var</literal> turn their argument into a lambda functor, that implements an identity mapping.
1390 The former two are for constants, the latter for variables. 
1391 The use of these <emphasis>delayed</emphasis> constants and variables is sometimes necessary due to the lack of explicit syntax for lambda expressions. 
1392 For example:
1393 <programlisting>
1394 <![CDATA[for_each(a.begin(), a.end(), cout << _1 << ' ');
1395 for_each(a.begin(), a.end(), cout << ' ' << _1);]]>
1396 </programlisting>
1397 The first line outputs the elements of <literal>a</literal> separated by spaces, while the second line outputs a space followed by the elements of <literal>a</literal> without any separators.
1398 The reason for this is that neither of the operands of 
1399 <literal><![CDATA[cout << ' ']]></literal> is a lambda expression, hence <literal><![CDATA[cout << ' ']]></literal> is evaluated immediately.
1400
1401 To delay the evaluation of <literal><![CDATA[cout << ' ']]></literal>, one of the operands must be explicitly marked as a lambda expression. 
1402 This is accomplished with the <literal>constant</literal> function:
1403 <programlisting>
1404 <![CDATA[for_each(a.begin(), a.end(), cout << constant(' ') << _1);]]>
1405 </programlisting>
1406
1407 The call <literal>constant(' ')</literal> creates a nullary lambda functor which stores the character constant <literal>' '</literal> 
1408 and returns a reference to it when invoked. 
1409 The function <literal>constant_ref</literal> is similar, except that it
1410 stores a constant reference to its argument.
1411
1412 The <literal>constant</literal> and <literal>consant_ref</literal> are only
1413 needed when the operator call has side effects, like in the above example.
1414 </para>
1415
1416 <para>
1417 Sometimes we need to delay the evaluation of a variable. 
1418 Suppose we wanted to output the elements of a container in a numbered list:
1419
1420 <programlisting>
1421 <![CDATA[int index = 0; 
1422 for_each(a.begin(), a.end(), cout << ++index << ':' << _1 << '\n');
1423 for_each(a.begin(), a.end(), cout << ++var(index) << ':' << _1 << '\n');]]>
1424 </programlisting>
1425
1426 The first <literal>for_each</literal> invocation does not do what we want; <literal>index</literal> is incremented only once, and its value is written into the output stream only once.
1427 By using <literal>var</literal> to make <literal>index</literal> a lambda expression, we get the desired effect.
1428 <!-- Note that <literal>var</literal> accepts const objects as well, in which case
1429 calling <literal>var</literal> equals calling <literal>constant_ref</literal>.-->
1430 </para>
1431
1432 <para>
1433 In sum, <literal>var(x)</literal> creates a nullary lambda functor, 
1434 which stores a reference to the variable <literal>x</literal>. 
1435 When the lambda functor is invoked, a reference to <literal>x</literal> is returned.
1436 </para>
1437
1438 <simplesect>
1439 <title>Naming delayed constants and variables</title>
1440
1441 <para>
1442 It is possible to predefine and name a delayed variable or constant outside a lambda expression. 
1443 The templates <literal>var_type</literal>, <literal>constant_type</literal> 
1444 and <literal>constant_ref_type</literal> serve for this purpose. 
1445 They are used as:
1446 <programlisting>
1447 <![CDATA[var_type<T>::type delayed_i(var(i));
1448 constant_type<T>::type delayed_c(constant(c));]]>
1449 </programlisting>
1450 The first line defines the variable <literal>delayed_i</literal> which is a delayed version of the variable <literal>i</literal> of type <literal>T</literal>.
1451 Analogously, the second line defines the constant <literal>delayed_c</literal> as a delayed version of the constant <literal>c</literal>.
1452 For example:
1453
1454 <programlisting>
1455 int i = 0; int j;
1456 for_each(a.begin(), a.end(), (var(j) = _1, _1 = var(i), var(i) = var(j))); 
1457 </programlisting>
1458 is equivalent to:
1459 <programlisting>
1460 <![CDATA[int i = 0; int j;
1461 var_type<int>::type vi(var(i)), vj(var(j));
1462 for_each(a.begin(), a.end(), (vj = _1, _1 = vi, vi = vj));]]>
1463 </programlisting>
1464 </para>
1465 <para>
1466 Here is an example of naming a delayed constant:
1467 <programlisting>
1468 <![CDATA[constant_type<char>::type space(constant(' '));
1469 for_each(a.begin(),a.end(), cout << space << _1);]]>
1470 </programlisting>
1471 </para>
1472
1473 </simplesect>
1474
1475 <simplesect>
1476 <title>About assignment and subscript operators</title>
1477
1478 <para>
1479 As described in <xref linkend="sect:assignment_and_subscript"/>, assignment and subscripting operators are always defined as member functions.
1480 This means, that for expressions of the form
1481 <literal>x = y</literal> or <literal>x[y]</literal> to be interpreted as lambda expressions, the left-hand operand <literal>x</literal> must be a lambda expression. 
1482 Consequently, it is sometimes necessary to use <literal>var</literal> for this purpose.
1483 We repeat the example from <xref linkend="sect:assignment_and_subscript"/>:
1484
1485 <programlisting>
1486 int i; 
1487 i = _1;       // error
1488 var(i) = _1;  // ok
1489 </programlisting>
1490 </para>
1491
1492 <para>
1493
1494 Note that the compound assignment operators <literal>+=</literal>, <literal>-=</literal> 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.
1495 Nevertheless, it is perfectly ok to delay the left operand explicitly. 
1496 For example, <literal>i += _1</literal> is equivalent to <literal>var(i) += _1</literal>.
1497 </para>
1498 </simplesect>
1499
1500 </section>
1501
1502 <section id="sect:lambda_expressions_for_control_structures">
1503 <title>Lambda expressions for control structures</title>
1504
1505 <para>
1506 BLL defines several functions to create lambda functors that represent control structures. 
1507 They all take lambda functors as parameters and return <literal>void</literal>.
1508 To start with an example, the following code outputs all even elements of some container <literal>a</literal>:
1509
1510 <programlisting>
1511 <![CDATA[for_each(a.begin(), a.end(), 
1512          if_then(_1 % 2 == 0, cout << _1));]]>  
1513 </programlisting>
1514 </para>
1515
1516 <para>
1517 The BLL supports the following function templates for control structures: 
1518
1519 <programlisting>
1520 if_then(condition, then_part)
1521 if_then_else(condition, then_part, else_part)
1522 if_then_else_return(condition, then_part, else_part)
1523 while_loop(condition, body)
1524 while_loop(condition) // no body case
1525 do_while_loop(condition, body)
1526 do_while_loop(condition) // no body case 
1527 for_loop(init, condition, increment, body)
1528 for_loop(init, condition, increment) // no body case
1529 switch_statement(...)
1530 </programlisting>
1531
1532 The return types of all control construct lambda functor is 
1533 <literal>void</literal>, except for <literal>if_then_else_return</literal>,
1534 which wraps a call to the conditional operator 
1535 <programlisting>
1536 condition ? then_part : else_part
1537 </programlisting>
1538 The return type rules for this operator are somewhat complex. 
1539 Basically, if the branches have the same type, this type is the return type.
1540 If the type of the branches differ, one branch, say of type 
1541 <literal>A</literal>, must be convertible to the other branch, 
1542 say of type <literal>B</literal>.
1543 In this situation, the result type is <literal>B</literal>.
1544 Further, if the common type is an lvalue, the return type will be an lvalue
1545 too.
1546 </para>
1547
1548
1549 <para>
1550 Delayed variables tend to be commonplace in control structure lambda expressions. 
1551 For instance, here we use the <literal>var</literal> function to turn the arguments of <literal>for_loop</literal> into lambda expressions. 
1552 The effect of the code is to add 1 to each element of a two-dimensional array:
1553
1554 <programlisting>
1555 <![CDATA[int a[5][10]; int i;
1556 for_each(a, a+5, 
1557   for_loop(var(i)=0, var(i)<10, ++var(i), 
1558            _1[var(i)] += 1));]]>  
1559 </programlisting>
1560
1561 <!--
1562 As explained in <xref linkend="sect:delaying_constants_and_variables"/>, we can avoid the repeated use of wrapping of <literal>var</literal> if we define it beforehand:
1563
1564 <programlisting>
1565 <![CDATA[int i;
1566 var_type<int>::type vi(var(i));
1567 for_each(a, a+5, 
1568   for_loop(vi=0, vi<10, ++vi, _1[vi] += 6));]]>  
1569 </programlisting>
1570
1571 -->
1572 </para>
1573
1574 <para>
1575 The BLL supports an alternative syntax for control expressions, suggested
1576 by Joel de Guzmann. 
1577 By overloading the <literal>operator[]</literal> we can
1578 get a closer resemblance with the built-in control structures:
1579
1580 <programlisting>
1581 <![CDATA[if_(condition)[then_part]
1582 if_(condition)[then_part].else_[else_part]
1583 while_(condition)[body]
1584 do_[body].while_(condition)
1585 for_(init, condition, increment)[body]]]>
1586 </programlisting>
1587
1588 For example, using this syntax the <literal>if_then</literal> example above
1589 can be written as:
1590 <programlisting>
1591 <![CDATA[for_each(a.begin(), a.end(), 
1592          if_(_1 % 2 == 0)[ cout << _1 ])]]>  
1593 </programlisting>
1594
1595 As more experience is gained, we may end up deprecating one or the other 
1596 of these syntaces. 
1597
1598 </para>
1599
1600
1601
1602 <section id="sect:switch_statement">
1603 <title>Switch statement</title>
1604 </section>
1605
1606 <para>
1607 The lambda expressions for <literal>switch</literal> control structures are more complex since the number of cases may vary. 
1608 The general form of a switch lambda expression is:
1609
1610 <programlisting>
1611 switch_statement(<parameter>condition</parameter>, 
1612   case_statement&lt;<parameter>label</parameter>&gt;(<parameter>lambda expression</parameter>),
1613   case_statement&lt;<parameter>label</parameter>&gt;(<parameter>lambda expression</parameter>),
1614   ...
1615   default_statement(<parameter>lambda expression</parameter>)
1616 )
1617 </programlisting>
1618
1619 The <literal><parameter>condition</parameter></literal> argument must be a lambda expression that creates a lambda functor with an integral return type.
1620 The different cases are created with the <literal>case_statement</literal> functions, and the optional default case with the <literal>default_statement</literal> function.
1621 The case labels are given as explicitly specified template arguments to <literal>case_statement</literal> functions and 
1622 <literal>break</literal> statements are implicitly part of each case. 
1623 For example, <literal><![CDATA[case_statement<1>(a)]]></literal>, where <literal>a</literal> is some lambda functor,  generates the code:
1624
1625 <programlisting>
1626 case 1: 
1627   <parameter>evaluate lambda functor</parameter> a; 
1628   break;
1629 </programlisting>
1630 The <literal>switch_statement</literal> function is specialized for up to 9 case statements.
1631
1632 </para>
1633
1634 <para>
1635 As a concrete example, the following code iterates over some container <literal>v</literal> and ouptuts <quote>zero</quote> for each <literal>0</literal>, <quote>one</quote> for each <literal>1</literal>, and <quote>other: <parameter>n</parameter></quote> for any other value <parameter>n</parameter>.
1636 Note that another lambda expression is sequenced after the <literal>switch_statement</literal> to output a line break after each element:
1637
1638 <programlisting>
1639 <![CDATA[std::for_each(v.begin(), v.end(),
1640   ( 
1641     switch_statement(
1642       _1,
1643       case_statement<0>(std::cout << constant("zero")),
1644       case_statement<1>(std::cout << constant("one")),
1645       default_statement(cout << constant("other: ") << _1)
1646     ), 
1647     cout << constant("\n") 
1648   )
1649 );]]>
1650 </programlisting>
1651 </para>
1652
1653 </section>
1654
1655 <section id="sect:exceptions">
1656 <title>Exceptions</title>
1657
1658 <para>
1659 The BLL provides lambda functors that throw and catch exceptions.
1660 Lambda functors for throwing exceptions are created with the unary function <literal>throw_exception</literal>.
1661 The argument to this function is the exception to be thrown, or a lambda functor which creates the exception to be thrown.
1662 A lambda functor for rethrowing exceptions is created with the nullary <literal>rethrow</literal> function.
1663 </para>
1664
1665 <para>
1666 Lambda expressions for handling exceptions are somewhat more complex.
1667 The general form of a lambda expression for try catch blocks is as follows:
1668
1669 <programlisting>
1670 try_catch(
1671   <parameter>lambda expression</parameter>,
1672   catch_exception&lt;<parameter>type</parameter>&gt;(<parameter>lambda expression</parameter>),
1673   catch_exception&lt;<parameter>type</parameter>&gt;(<parameter>lambda expression</parameter>),
1674   ...
1675   catch_all(<parameter>lambda expression</parameter>)
1676 )
1677 </programlisting>
1678
1679 The first lambda expression is the try block. 
1680 Each <literal>catch_exception</literal> defines a catch block where the 
1681 explicitly specified template argument defines the type of the exception 
1682 to catch.
1683
1684 The lambda expression within the <literal>catch_exception</literal> defines 
1685 the actions to take if the exception is caught.
1686
1687 Note that the resulting exception handlers catch the exceptions as 
1688 references, i.e., <literal>catch_exception&lt;T&gt;(...)</literal> 
1689 results in the catch block:
1690
1691 <programlisting>
1692 catch(T&amp; e) { ... }
1693 </programlisting>
1694
1695 The last catch block can alternatively be a call to 
1696 <literal>catch_exception&lt;<parameter>type</parameter>&gt;</literal> 
1697 or to 
1698 <literal>catch_all</literal>, which is the lambda expression equivalent to 
1699 <literal>catch(...)</literal>.
1700
1701 </para>
1702
1703 <para>
1704
1705 The <xref linkend="ex:exceptions"/> demonstrates the use of the BLL 
1706 exception handling tools. 
1707 The first handler catches exceptions of type <literal>foo_exception</literal>. 
1708 Note the use of <literal>_1</literal> placeholder in the body of the handler.
1709 </para>
1710
1711 <para>
1712 The second handler shows how to throw exceptions, and demonstrates the 
1713 use of the <emphasis>exception placeholder</emphasis> <literal>_e</literal>.
1714
1715 It is a special placeholder, which refers to the caught exception object 
1716 within the handler body.
1717
1718 Here we are handling an exception of type <literal>std::exception</literal>, 
1719 which carries a string explaining the cause of the exception. 
1720
1721 This explanation can be queried with the zero-argument member 
1722 function <literal>what</literal>.
1723
1724 The expression
1725 <literal>bind(&amp;std::exception::what, _e)</literal> creates the lambda 
1726 function for making that call.
1727
1728 Note that <literal>_e</literal> cannot be used outside of an exception handler lambda expression.
1729 <!--Violating this rule is caught by the compiler.-->
1730
1731 The last line of the second handler constructs a new exception object and 
1732 throws that with <literal>throw exception</literal>. 
1733
1734 Constructing and destructing objects within lambda expressions is 
1735 explained in <xref linkend="sect:construction_and_destruction"/>
1736 </para>
1737
1738 <para>
1739 Finally, the third handler (<literal>catch_all</literal>) demonstrates 
1740 rethrowing exceptions.
1741 </para>
1742
1743 <example id="ex:exceptions">
1744 <title>Throwing and handling exceptions in lambda expressions.</title>
1745 <programlisting>
1746 <![CDATA[for_each(
1747   a.begin(), a.end(),
1748   try_catch(
1749     bind(foo, _1),                 // foo may throw
1750     catch_exception<foo_exception>(
1751       cout << constant("Caught foo_exception: ") 
1752            << "foo was called with argument = " << _1
1753     ),
1754     catch_exception<std::exception>(
1755       cout << constant("Caught std::exception: ") 
1756            << bind(&std::exception::what, _e),
1757       throw_exception(bind(constructor<bar_exception>(), _1)))
1758     ),      
1759     catch_all(
1760       (cout << constant("Unknown"), rethrow())
1761     )
1762   )
1763 );]]>
1764 </programlisting>
1765 </example>
1766
1767 </section>
1768
1769 <section id="sect:construction_and_destruction">
1770 <title>Construction and destruction</title>
1771
1772
1773 <para>
1774 Operators <literal>new</literal> and <literal>delete</literal> can be 
1775 overloaded, but their return types are fixed. 
1776
1777 Particularly, the return types cannot be lambda functors, 
1778 which prevents them to be overloaded for lambda expressions.
1779
1780 It is not possible to take the address of a constructor, 
1781 hence constructors cannot be used as target functions in bind expressions.
1782
1783 The same is true for destructors.
1784
1785 As a way around these constraints, BLL defines wrapper classes for 
1786 <literal>new</literal> and <literal>delete</literal> calls, 
1787 as well as for constructors and destructors.
1788
1789 Instances of these classes are function objects, that can be used as 
1790 target functions of bind expressions. 
1791
1792 For example:
1793
1794 <programlisting>
1795 <![CDATA[int* a[10];
1796 for_each(a, a+10, _1 = bind(new_ptr<int>())); 
1797 for_each(a, a+10, bind(delete_ptr(), _1));]]>
1798 </programlisting>
1799
1800 The <literal>new_ptr&lt;int&gt;()</literal> expression creates 
1801 a function object that calls <literal>new int()</literal> when invoked, 
1802 and wrapping that inside <literal>bind</literal> makes it a lambda functor.
1803
1804 In the same way, the expression <literal>delete_ptr()</literal> creates 
1805 a function object that invokes <literal>delete</literal> on its argument. 
1806
1807 Note that <literal>new_ptr&lt;<parameter>T</parameter>&gt;()</literal> 
1808 can take arguments as well.
1809
1810 They are passed directly to the constructor invocation and thus allow 
1811 calls to constructors which take arguments. 
1812
1813 </para>
1814
1815 <para>
1816
1817 As an example of constructor calls in lambda expressions, 
1818 the following code reads integers from two containers <literal>x</literal> 
1819 and <literal>y</literal>, 
1820 constructs pairs out of them and inserts them into a third container:
1821
1822 <programlisting>
1823 <![CDATA[vector<pair<int, int> > v;
1824 transform(x.begin(), x.end(), y.begin(), back_inserter(v),
1825           bind(constructor<pair<int, int> >(), _1, _2));]]>
1826 </programlisting>
1827
1828 <xref linkend="table:constructor_destructor_fos"/> lists all the function 
1829 objects related to creating and destroying objects,
1830  showing the expression to create and call the function object, 
1831 and the effect of evaluating that expression.
1832
1833 </para>
1834
1835
1836
1837 <table id="table:constructor_destructor_fos">
1838 <title>Construction and destruction related function objects.</title>
1839 <tgroup cols="2">
1840 <thead>
1841 <row>
1842 <entry>Function object call</entry>
1843 <entry>Wrapped expression</entry>
1844 </row>
1845 </thead>
1846 <tbody>
1847 <row>
1848 <entry><literal>constructor&lt;T&gt;()(<parameter>arg_list</parameter>)</literal></entry>
1849 <entry>T(<parameter>arg_list</parameter>)</entry>
1850 </row>
1851 <row>
1852 <entry><literal>destructor()(a)</literal></entry>
1853 <entry><literal>a.~A()</literal>, where <literal>a</literal> is of type <literal>A</literal></entry>
1854 </row>
1855 <row>
1856 <entry><literal>destructor()(pa)</literal></entry>
1857 <entry><literal>pa->~A()</literal>, where <literal>pa</literal> is of type <literal>A*</literal></entry>
1858 </row>
1859 <row>
1860 <entry><literal>new_ptr&lt;T&gt;()(<parameter>arg_list</parameter>)</literal></entry>
1861 <entry><literal>new T(<parameter>arg_list</parameter>)</literal></entry>
1862 </row>
1863 <row>
1864 <entry><literal>new_array&lt;T&gt;()(sz)</literal></entry>
1865 <entry><literal>new T[sz]</literal></entry>
1866 </row>
1867 <row>
1868 <entry><literal>delete_ptr()(p)</literal></entry>
1869 <entry><literal>delete p</literal></entry>
1870 </row>
1871 <row>
1872 <entry><literal>delete_array()(p)</literal></entry>
1873 <entry><literal>delete p[]</literal></entry>
1874 </row>
1875
1876
1877 </tbody>
1878 </tgroup>
1879 </table> 
1880
1881 </section>
1882
1883
1884 <section>
1885 <title>Special lambda expressions</title>
1886
1887 <section>
1888 <title>Preventing argument substitution</title>
1889
1890 <para>
1891 When a lambda functor is called, the default behavior is to substitute 
1892 the actual arguments for the placeholders within all subexpressions.
1893
1894 This section describes the tools to prevent the substitution and 
1895 evaluation of a subexpression, and explains when these tools should be used.
1896 </para>
1897
1898
1899 <para>
1900 The arguments to a bind expression can be arbitrary lambda expressions, 
1901 e.g., other bind expressions.
1902
1903 For example:
1904
1905 <programlisting>
1906 int foo(int); int bar(int);
1907 ...
1908 int i;
1909 bind(foo, bind(bar, _1)(i);
1910 </programlisting>
1911
1912 The last line makes the call <literal>foo(bar(i));</literal>
1913
1914 Note that the first argument in a bind expression, the target function, 
1915 is no exception, and can thus be a bind expression too.
1916
1917 The innermost lambda functor just has to return something that can be used 
1918 as a target function: another lambda functor, function pointer, 
1919 pointer to member function etc. 
1920
1921 For example, in the following code the innermost lambda functor makes 
1922 a selection between two functions, and returns a pointer to one of them:
1923
1924 <programlisting>
1925 int add(int a, int b) { return a+b; }
1926 int mul(int a, int b) { return a*b; }
1927
1928 int(*)(int, int)  add_or_mul(bool x) { 
1929   return x ? add : mul; 
1930 }
1931
1932 bool condition; int i; int j;
1933 ...
1934 bind(bind(&amp;add_or_mul, _1), _2, _3)(condition, i, j);
1935 </programlisting>
1936
1937 </para>
1938
1939
1940
1941 <section id="sect:unlambda">
1942 <title>Unlambda</title>
1943
1944 <para>A nested bind expression may occur inadvertently, 
1945 if the target function is a variable with a type that depends on a 
1946 template parameter. 
1947
1948 Typically the target function could be a formal parameter of a 
1949 function template. 
1950
1951 In such a case, the programmer may not know whether the target function is a lambda functor or not.
1952 </para>
1953
1954 <para>Consider the following function template:
1955
1956 <programlisting>
1957 <![CDATA[template<class F>
1958 int nested(const F& f) {
1959   int x;
1960   ...
1961   bind(f, _1)(x);
1962   ...
1963 }]]>
1964 </programlisting>
1965
1966 Somewhere inside the function the formal parameter
1967 <literal>f</literal> is used as a target function in a bind expression. 
1968
1969 In order for this <literal>bind</literal> call to be valid, 
1970 <literal>f</literal> must be a unary function.
1971
1972 Suppose the following two calls to <literal>nested</literal> are made:
1973
1974 <programlisting>
1975 <![CDATA[int foo(int);
1976 int bar(int, int);
1977 nested(&foo);
1978 nested(bind(bar, 1, _1));]]>
1979 </programlisting>
1980
1981 Both are unary functions, or function objects, with appropriate argument 
1982 and return types, but the latter will not compile.
1983
1984 In the latter call, the bind expression inside <literal>nested</literal> 
1985 will become:
1986
1987 <programlisting>
1988 bind(bind(bar, 1, _1), _1) 
1989 </programlisting>
1990
1991 When this is invoked with <literal>x</literal>, 
1992 after substituitions we end up trying to call
1993
1994 <programlisting>
1995 bar(1, x)(x)
1996 </programlisting>
1997
1998 which is an error. 
1999
2000 The call to <literal>bar</literal> returns int, 
2001 not a unary function or function object.
2002 </para>
2003
2004 <para>
2005 In the example above, the intent of the bind expression in the 
2006 <literal>nested</literal> function is to treat <literal>f</literal> 
2007 as an ordinary function object, instead of a lambda functor. 
2008
2009 The BLL provides the function template <literal>unlambda</literal> to 
2010 express this: a lambda functor wrapped inside <literal>unlambda</literal> 
2011 is not a lambda functor anymore, and does not take part into the 
2012 argument substitution process.
2013
2014 Note that for all other argument types <literal>unlambda</literal> is 
2015 an identity operation, except for making non-const objects const.
2016 </para>
2017
2018 <para>
2019 Using <literal>unlambda</literal>, the <literal>nested</literal> 
2020 function is written as:
2021
2022 <programlisting>
2023 <![CDATA[template<class F>
2024 int nested(const F& f) {
2025   int x;
2026   ...
2027   bind(unlambda(f), _1)(x);
2028   ...
2029 }]]>
2030 </programlisting>
2031
2032 </para>
2033
2034 </section>
2035
2036 <section>
2037 <title>Protect</title>
2038
2039 <para>
2040 The <literal>protect</literal> function is related to unlambda. 
2041
2042 It is also used to prevent the argument substitution taking place, 
2043 but whereas <literal>unlambda</literal> turns a lambda functor into 
2044 an ordinary function object for good, <literal>protect</literal> does 
2045 this temporarily, for just one evaluation round.
2046
2047 For example:
2048
2049 <programlisting>
2050 int x = 1, y = 10;
2051 (_1 + protect(_1 + 2))(x)(y);
2052 </programlisting>
2053     
2054 The first call substitutes <literal>x</literal> for the leftmost 
2055 <literal>_1</literal>, and results in another lambda functor 
2056 <literal>x + (_1 + 2)</literal>, which after the call with 
2057 <literal>y</literal> becomes <literal>x + (y + 2)</literal>, 
2058 and thus finally 13.
2059 </para>
2060
2061 <para>
2062 Primary motivation for including <literal>protect</literal> into the library, 
2063 was to allow nested STL algorithm invocations 
2064 (<xref linkend="sect:nested_stl_algorithms"/>).
2065 </para>
2066
2067 </section>
2068
2069 </section>
2070
2071 <section id="sect:rvalues_as_actual_arguments">
2072 <title>Rvalues as actual arguments to lambda functors</title>
2073
2074       <para><emphasis>This section and all of its subsections
2075        are no longer (or currently) relevant;
2076        acual arguments can be non-const rvalues and these workarounds are thus
2077        not needed.
2078        The section can, however, become relevant again, if in the future BLL will support
2079        lambda functors with higher arities than 3.</emphasis></para>
2080
2081 <para>
2082 Actual arguments to the lambda functors cannot be non-const rvalues.
2083 This is due to a deliberate design decision: either we have this restriction, 
2084 or there can be no side-effects to the actual arguments.
2085
2086 There are ways around this limitation.
2087
2088 We repeat the example from section 
2089 <xref linkend="sect:actual_arguments_to_lambda_functors"/> and list the 
2090 different solutions:
2091
2092 <programlisting>
2093 int i = 1; int j = 2; 
2094 (_1 + _2)(i, j); // ok
2095 (_1 + _2)(1, 2); // error (!)
2096 </programlisting>
2097
2098 <orderedlist>
2099 <listitem>
2100 <para>
2101 If the rvalue is of a class type, the return type of the function that 
2102 creates the rvalue should be defined as const. 
2103 Due to an unfortunate language restriction this does not work for 
2104 built-in types, as built-in rvalues cannot be const qualified. 
2105 </para>
2106 </listitem>
2107
2108 <listitem>
2109 <para>
2110 If the lambda function call is accessible, the <literal>make_const</literal> 
2111 function can be used to <emphasis>constify</emphasis> the rvalue. E.g.:
2112
2113 <programlisting>
2114 (_1 + _2)(make_const(1), make_const(2)); // ok
2115 </programlisting>
2116
2117 Commonly the lambda function call site is inside a standard algorithm 
2118 function template, preventing this solution to be used.
2119
2120 </para>
2121 </listitem>
2122
2123 <listitem>
2124 <para>
2125 If neither of the above is possible, the lambda expression can be wrapped 
2126 in a <literal>const_parameters</literal> function. 
2127 It creates another type of lambda functor, which takes its arguments as 
2128 const references. For example:
2129
2130 <programlisting>
2131 const_parameters(_1 + _2)(1, 2); // ok
2132 </programlisting>
2133
2134 Note that <literal>const_parameters</literal> makes all arguments const.
2135 Hence, in the case were one of the arguments is a non-const rvalue, 
2136 and another argument needs to be passed as a non-const reference, 
2137 this approach cannot be used.
2138 </para>
2139
2140 </listitem>
2141
2142 <listitem>
2143 <para>If none of the above is possible, there is still one solution, 
2144 which unfortunately can break const correctness.
2145
2146 The solution is yet another lambda functor wrapper, which we have named 
2147 <literal>break_const</literal> to alert the user of the potential dangers 
2148 of this function. 
2149
2150 The <literal>break_const</literal> function creates a lambda functor that 
2151 takes its arguments as const, and casts away constness prior to the call 
2152 to the original wrapped lambda functor.
2153
2154 For example:
2155 <programlisting>
2156 int i; 
2157 ...
2158 (_1 += _2)(i, 2);                 // error, 2 is a non-const rvalue
2159 const_parameters(_1 += _2)(i, 2); // error, i becomes const
2160 break_const(_1 += _2)(i, 2);      // ok, but dangerous
2161 </programlisting>
2162
2163 Note, that the results of <literal> break_const</literal> or 
2164 <literal>const_parameters</literal> are not lambda functors, 
2165 so they cannot be used as subexpressions of lambda expressions. For instance:
2166
2167 <programlisting>
2168 break_const(_1 + _2) + _3; // fails.
2169 const_parameters(_1 + _2) + _3; // fails.
2170 </programlisting>
2171
2172 However, this kind of code should never be necessary, 
2173 since calls to sub lambda functors are made inside the BLL, 
2174 and are not affected by the non-const rvalue problem.
2175 </para>
2176 </listitem>
2177
2178 </orderedlist>
2179
2180 </para>
2181 </section>
2182
2183 </section>
2184
2185
2186 <section>
2187 <title>Casts, sizeof and typeid</title>
2188
2189 <section id="sect:cast_expressions">
2190 <title>
2191 Cast expressions
2192 </title>
2193 <para>
2194 The BLL defines its counterparts for the four cast expressions 
2195 <literal>static_cast</literal>, <literal>dynamic_cast</literal>, 
2196 <literal>const_cast</literal> and <literal>reinterpret_cast</literal>.
2197
2198 The BLL versions of the cast expressions have the prefix 
2199 <literal>ll_</literal>.
2200
2201 The type to cast to is given as an explicitly specified template argument, 
2202 and the sole argument is the expression from which to perform the cast.
2203
2204 If the argument is a lambda functor, the lambda functor is evaluated first.
2205
2206 For example, the following code uses <literal>ll_dynamic_cast</literal> 
2207 to count the number of <literal>derived</literal> instances in the container 
2208 <literal>a</literal>:
2209
2210 <programlisting>
2211 <![CDATA[class base {};
2212 class derived : public base {};
2213
2214 vector<base*> a;
2215 ...
2216 int count = 0;
2217 for_each(a.begin(), a.end(), 
2218          if_then(ll_dynamic_cast<derived*>(_1), ++var(count)));]]>
2219 </programlisting>
2220 </para>
2221 </section>
2222
2223 <section>
2224 <title>Sizeof and typeid</title>
2225 <para>
2226 The BLL counterparts for these expressions are named 
2227 <literal>ll_sizeof</literal> and <literal>ll_typeid</literal>.
2228
2229 Both take one argument, which can be a lambda expression.
2230 The lambda functor created wraps the <literal>sizeof</literal> or 
2231 <literal>typeid</literal> call, and when the lambda functor is called 
2232 the wrapped operation is performed.
2233
2234 For example:
2235
2236 <programlisting>
2237 <![CDATA[vector<base*> a; 
2238 ...
2239 for_each(a.begin(), a.end(), 
2240          cout << bind(&type_info::name, ll_typeid(*_1)));]]>
2241 </programlisting>
2242
2243 Here <literal>ll_typeid</literal> creates a lambda functor for 
2244 calling <literal>typeid</literal> for each element.
2245
2246 The result of a <literal>typeid</literal> call is an instance of 
2247 the <literal>type_info</literal> class, and the bind expression creates 
2248 a lambda functor for calling the <literal>name</literal> member 
2249 function of that class.
2250
2251 </para>
2252 </section>
2253
2254
2255
2256 </section>
2257
2258 <section id="sect:nested_stl_algorithms">
2259 <title>Nesting STL algorithm invocations</title>
2260
2261 <para>
2262 The BLL defines common STL algorithms as function object classes, 
2263 instances of which can be used as target functions in bind expressions.
2264 For example, the following code iterates over the elements of a 
2265 two-dimensional array, and computes their sum.
2266
2267 <programlisting>
2268 int a[100][200];
2269 int sum = 0;
2270
2271 std::for_each(a, a + 100, 
2272               bind(ll::for_each(), _1, _1 + 200, protect(sum += _1)));
2273 </programlisting>
2274
2275 The 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 <literal>std</literal> namespace.
2276 All these structs are placed in the subnamespace <literal>boost::lambda:ll</literal>. 
2277 <!--The supported algorithms are listed in <xref linkend="table:nested_algorithms"/>.-->
2278 </para>
2279
2280 <para>
2281 Note that there is no easy way to express an overloaded member function 
2282 call in a lambda expression. 
2283
2284 This limits the usefulness of nested STL algorithms, as for instance 
2285 the <literal>begin</literal> function has more than one overloaded 
2286 definitions in container templates.
2287
2288 In general, something analogous to the pseudo-code below cannot be written:
2289
2290 <programlisting>
2291 std::for_each(a.begin(), a.end(), 
2292               bind(ll::for_each(), _1.begin(), _1.end(), protect(sum += _1)));
2293 </programlisting>
2294
2295 Some aid for common special cases can be provided though.
2296
2297 The BLL defines two helper function object classes, 
2298 <literal>call_begin</literal> and <literal>call_end</literal>, 
2299 which wrap a call to the <literal>begin</literal> and, respectively, 
2300 <literal>end</literal> functions of a container, and return the 
2301 <literal>const_iterator</literal> type of the container.
2302
2303 With these helper templates, the above code becomes:
2304 <programlisting>
2305 std::for_each(a.begin(), a.end(), 
2306               bind(ll::for_each(), 
2307                    bind(call_begin(), _1), bind(call_end(), _1),
2308                         protect(sum += _1)));
2309 </programlisting>
2310
2311 </para>
2312
2313 <!--
2314 <table id="table:nested_algorithms">
2315 <title>The nested STL algorithms.</title>
2316 <tgroup cols="1">
2317 <thead>
2318 <trow><entry>Otsikko</entry></trow>
2319 </thead>
2320 <tbody>
2321 <row><entry><literal>for_each</literal></entry></row>
2322 <row><entry><literal>find</literal></entry></row>
2323 <row><entry><literal>find_if</literal></entry></row>
2324 <row><entry><literal>find_end</literal></entry></row>
2325 <row><entry><literal>find_first_of</literal></entry></row>
2326 <row><entry><literal>transform</literal></entry></row>
2327 </tbody>
2328 </tgroup>
2329
2330 </table>
2331
2332 -->
2333
2334 </section>
2335
2336
2337 </section>
2338
2339
2340 <!--
2341 <section>
2342 <title>Common gothcas</title>
2343
2344 calling member functions a.begin() 
2345
2346 calling templated functions ...
2347
2348 </section>
2349
2350 -->
2351
2352 <section id="sect:extending_return_type_system">
2353 <title>Extending return type deduction system</title>
2354
2355 <para>
2356 <!--The <xref linkend = "sect:overriding_deduced_return_type"/> showed how to make BLL aware of the return type of a function object in bind expressions.-->
2357
2358 In this section, we explain  how to extend the return type deduction system 
2359 to cover user defined operators. 
2360
2361 In many cases this is not necessary, 
2362 as the BLL defines default return types for operators.
2363
2364 For example, the default return type for all comparison operators is 
2365 <literal>bool</literal>, and as long as the user defined comparison operators 
2366 have a bool return type, there is no need to write new specializations 
2367 for the return type deduction classes.
2368
2369 Sometimes this cannot be avoided, though.
2370
2371 </para>
2372
2373 <para>
2374 The overloadable user defined operators are either unary or binary. 
2375
2376 For each arity, there are two traits templates that define the 
2377 return types of the different operators.
2378
2379 Hence, the return type system can be extended by providing more 
2380 specializations for these templates.
2381
2382 The templates for unary functors are
2383
2384 <literal>
2385 <![CDATA[plain_return_type_1<Action, A>]]>
2386 </literal>
2387
2388 and 
2389
2390 <literal>
2391 <![CDATA[return_type_1<Action, A>]]>
2392 </literal>, and 
2393
2394 <literal>
2395 <![CDATA[plain_return_type_2<Action, A, B>]]>
2396 </literal>
2397
2398 and 
2399
2400 <literal>
2401 <![CDATA[return_type_2<Action, A, B>]]>
2402 </literal>
2403
2404 respectively for binary functors.
2405
2406 </para>
2407
2408 <para>
2409 The first parameter (<literal>Action</literal>) to all these templates 
2410 is the <emphasis>action</emphasis> class, which specifies the operator. 
2411
2412 Operators with similar return type rules are grouped together into 
2413 <emphasis>action groups</emphasis>, 
2414 and only the action class and action group together define the operator 
2415 unambiguously. 
2416
2417 As an example, the action type 
2418 <literal><![CDATA[arithmetic_action<plus_action>]]></literal> stands for 
2419 <literal>operator+</literal>. 
2420
2421 The complete listing of different action types is shown in 
2422 <xref linkend="table:actions"/>. 
2423 </para>
2424
2425 <para>
2426 The latter parameters, <literal>A</literal> in the unary case, 
2427 or <literal>A</literal> and <literal>B</literal> in the binary case, 
2428 stand for the argument types of the operator call. 
2429
2430 The two sets of templates, 
2431 <literal>plain_return_type_<parameter>n</parameter></literal> and 
2432 <literal>return_type_<parameter>n</parameter></literal> 
2433 (<parameter>n</parameter> is 1 or 2) differ in the way how parameter types 
2434 are presented to them.
2435
2436 For the former templates, the parameter types are always provided as 
2437 non-reference types, and do not have const or volatile qualifiers.
2438
2439 This makes specializing easy, as commonly one specialization for each 
2440 user defined operator, or operator group, is enough.
2441
2442 On the other hand, if a particular operator is overloaded for different 
2443 cv-qualifications of the same argument types, 
2444 and the return types of these overloaded versions differ, a more fine-grained control is needed.
2445
2446 Hence, for the latter templates, the parameter types preserve the 
2447 cv-qualifiers, and are non-reference types as well. 
2448  
2449 The downside is, that for an overloaded set of operators of the 
2450 kind described above, one may end up needing up to 
2451 16 <literal>return_type_2</literal> specializations.
2452 </para>
2453
2454 <para>
2455 Suppose the user has overloaded the following operators for some user defined 
2456 types <literal>X</literal>, <literal>Y</literal> and <literal>Z</literal>:
2457
2458 <programlisting>
2459 <![CDATA[Z operator+(const X&, const Y&);
2460 Z operator-(const X&, const Y&);]]>
2461 </programlisting>
2462
2463 Now, one can add a specialization stating, that if the left hand argument 
2464 is of type <literal>X</literal>, and the right hand one of type 
2465 <literal>Y</literal>, the return type of all such binary arithmetic 
2466 operators is <literal>Z</literal>:
2467
2468 <programlisting>
2469 <![CDATA[namespace boost { 
2470 namespace lambda {
2471   
2472 template<class Act> 
2473 struct plain_return_type_2<arithmetic_action<Act>, X, Y> {
2474   typedef Z type;
2475 };
2476
2477 }
2478 }]]>
2479 </programlisting>
2480
2481 Having this specialization defined, BLL is capable of correctly 
2482 deducing the return type of the above two operators.
2483
2484 Note, that the specializations must be in the same namespace, 
2485 <literal>::boost::lambda</literal>, with the primary template. 
2486
2487 For brevity, we do not show the namespace definitions in the examples below.
2488 </para>
2489
2490 <para>
2491 It is possible to specialize on the level of an individual operator as well, 
2492 in addition to providing a specialization for a group of operators. 
2493 Say, we add a new arithmetic operator for argument types <literal>X</literal> 
2494 and <literal>Y</literal>:
2495
2496 <programlisting>
2497 <![CDATA[X operator*(const X&, const Y&);]]>
2498 </programlisting>
2499
2500 Our first rule for all arithmetic operators specifies that the return 
2501 type of this operator is <literal>Z</literal>, 
2502 which obviously is not the case.
2503 Hence, we provide a new rule for the multiplication operator:
2504
2505 <programlisting>
2506 <![CDATA[template<> 
2507 struct plain_return_type_2<arithmetic_action<multiply_action>, X, Y> {
2508   typedef X type;
2509 };]]>
2510 </programlisting>
2511 </para>
2512
2513 <para>
2514 The specializations can define arbitrary mappings from the argument types 
2515 to the return type. 
2516
2517 Suppose we have some mathematical vector type, templated on the element type:
2518
2519 <programlisting>
2520 <![CDATA[template <class T> class my_vector;]]>
2521 </programlisting>
2522
2523 Suppose the addition operator is defined between any two 
2524 <literal>my_vector</literal> instantiations, 
2525 as long as the addition operator is defined between their element types. 
2526
2527 Furthermore, the element type of the resulting <literal>my_vector</literal> 
2528 is the same as the result type of the addition between the element types.
2529
2530 E.g., adding <literal><![CDATA[my_vector<int>]]></literal> and 
2531 <literal><![CDATA[my_vector<double>]]></literal> results in 
2532 <literal><![CDATA[my_vector<double>]]></literal>.
2533
2534 The BLL has traits classes to perform the implicit built-in and standard 
2535 type conversions between integral, floating point, and complex classes.
2536
2537 Using BLL tools, the addition operator described above can be defined as:
2538
2539 <programlisting>
2540 <![CDATA[template<class A, class B> 
2541 my_vector<typename return_type_2<arithmetic_action<plus_action>, A, B>::type>
2542 operator+(const my_vector<A>& a, const my_vector<B>& b)
2543 {
2544   typedef typename 
2545     return_type_2<arithmetic_action<plus_action>, A, B>::type res_type;
2546   return my_vector<res_type>();
2547 }]]>
2548 </programlisting>
2549 </para>
2550
2551 <para>
2552 To allow BLL to deduce the type of <literal>my_vector</literal> 
2553 additions correctly, we can define:
2554
2555 <programlisting>
2556 <![CDATA[template<class A, class B> 
2557 class plain_return_type_2<arithmetic_action<plus_action>, 
2558                            my_vector<A>, my_vector<B> > {
2559   typedef typename 
2560     return_type_2<arithmetic_action<plus_action>, A, B>::type res_type;
2561 public:
2562   typedef my_vector<res_type> type;
2563 };]]>
2564 </programlisting>
2565 Note, that we are reusing the existing specializations for the 
2566 BLL <literal>return_type_2</literal> template, 
2567 which require that the argument types are references. 
2568 </para>
2569
2570 <!-- TODO: is an example of specifying the other level needed at all -->
2571 <!-- TODO: comma operator is a special case for that -->
2572
2573 <table id = "table:actions">
2574 <title>Action types</title>
2575 <tgroup cols="2">
2576 <tbody>
2577
2578 <row><entry><literal><![CDATA[+]]></literal></entry><entry><literal><![CDATA[arithmetic_action<plus_action>]]></literal></entry></row>
2579 <row><entry><literal><![CDATA[-]]></literal></entry><entry><literal><![CDATA[arithmetic_action<minus_action>]]></literal></entry></row>
2580 <row><entry><literal><![CDATA[*]]></literal></entry><entry><literal><![CDATA[arithmetic_action<multiply_action>]]></literal></entry></row>
2581 <row><entry><literal><![CDATA[/]]></literal></entry><entry><literal><![CDATA[arithmetic_action<divide_action>]]></literal></entry></row>
2582 <row><entry><literal><![CDATA[%]]></literal></entry><entry><literal><![CDATA[arithmetic_action<remainder_action>]]></literal></entry></row>
2583
2584
2585
2586 <row><entry><literal><![CDATA[+]]></literal></entry><entry><literal><![CDATA[unary_arithmetic_action<plus_action>]]></literal></entry></row>
2587 <row><entry><literal><![CDATA[-]]></literal></entry><entry><literal><![CDATA[unary_arithmetic_action<minus_action>]]></literal></entry></row>
2588
2589
2590
2591 <row><entry><literal><![CDATA[&]]></literal></entry><entry><literal><![CDATA[bitwise_action<and_action>]]></literal></entry></row>
2592 <row><entry><literal><![CDATA[|]]></literal></entry><entry><literal><![CDATA[bitwise_action<or_action>]]></literal></entry></row>
2593 <row><entry><literal><![CDATA[~]]></literal></entry><entry><literal><![CDATA[bitwise_action<not_action>]]></literal></entry></row>
2594 <row><entry><literal><![CDATA[^]]></literal></entry><entry><literal><![CDATA[bitwise_action<xor_action>]]></literal></entry></row>
2595 <row><entry><literal><![CDATA[<<]]></literal></entry><entry><literal><![CDATA[bitwise_action<leftshift_action_no_stream>]]></literal></entry></row>
2596 <row><entry><literal><![CDATA[>>]]></literal></entry><entry><literal><![CDATA[bitwise_action<rightshift_action_no_stream>]]></literal></entry></row>
2597
2598
2599
2600 <row><entry><literal><![CDATA[&&]]></literal></entry><entry><literal><![CDATA[logical_action<and_action>]]></literal></entry></row>
2601 <row><entry><literal><![CDATA[||]]></literal></entry><entry><literal><![CDATA[logical_action<or_action>]]></literal></entry></row>
2602 <row><entry><literal><![CDATA[!]]></literal></entry><entry><literal><![CDATA[logical_action<not_action>]]></literal></entry></row>
2603
2604
2605
2606 <row><entry><literal><![CDATA[<]]></literal></entry><entry><literal><![CDATA[relational_action<less_action>]]></literal></entry></row>
2607 <row><entry><literal><![CDATA[>]]></literal></entry><entry><literal><![CDATA[relational_action<greater_action>]]></literal></entry></row>
2608 <row><entry><literal><![CDATA[<=]]></literal></entry><entry><literal><![CDATA[relational_action<lessorequal_action>]]></literal></entry></row>
2609 <row><entry><literal><![CDATA[>=]]></literal></entry><entry><literal><![CDATA[relational_action<greaterorequal_action>]]></literal></entry></row>
2610 <row><entry><literal><![CDATA[==]]></literal></entry><entry><literal><![CDATA[relational_action<equal_action>]]></literal></entry></row>
2611 <row><entry><literal><![CDATA[!=]]></literal></entry><entry><literal><![CDATA[relational_action<notequal_action>]]></literal></entry></row>
2612
2613
2614
2615 <row><entry><literal><![CDATA[+=]]></literal></entry><entry><literal><![CDATA[arithmetic_assignment_action<plus_action>]]></literal></entry></row>
2616 <row><entry><literal><![CDATA[-=]]></literal></entry><entry><literal><![CDATA[arithmetic_assignment_action<minus_action>]]></literal></entry></row>
2617 <row><entry><literal><![CDATA[*=]]></literal></entry><entry><literal><![CDATA[arithmetic_assignment_action<multiply_action>]]></literal></entry></row>
2618 <row><entry><literal><![CDATA[/=]]></literal></entry><entry><literal><![CDATA[arithmetic_assignment_action<divide_action>]]></literal></entry></row>
2619 <row><entry><literal><![CDATA[%=]]></literal></entry><entry><literal><![CDATA[arithmetic_assignment_action<remainder_action>]]></literal></entry></row>
2620
2621
2622
2623 <row><entry><literal><![CDATA[&=]]></literal></entry><entry><literal><![CDATA[bitwise_assignment_action<and_action>]]></literal></entry></row>
2624 <row><entry><literal><![CDATA[=|]]></literal></entry><entry><literal><![CDATA[bitwise_assignment_action<or_action>]]></literal></entry></row>
2625 <row><entry><literal><![CDATA[^=]]></literal></entry><entry><literal><![CDATA[bitwise_assignment_action<xor_action>]]></literal></entry></row>
2626 <row><entry><literal><![CDATA[<<=]]></literal></entry><entry><literal><![CDATA[bitwise_assignment_action<leftshift_action>]]></literal></entry></row>
2627 <row><entry><literal><![CDATA[>>=]]></literal></entry><entry><literal><![CDATA[bitwise_assignment_action<rightshift_action>]]></literal></entry></row>
2628
2629
2630
2631 <row><entry><literal><![CDATA[++]]></literal></entry><entry><literal><![CDATA[pre_increment_decrement_action<increment_action>]]></literal></entry></row>
2632 <row><entry><literal><![CDATA[--]]></literal></entry><entry><literal><![CDATA[pre_increment_decrement_action<decrement_action>]]></literal></entry></row>
2633 <row><entry><literal><![CDATA[++]]></literal></entry><entry><literal><![CDATA[post_increment_decrement_action<increment_action>]]></literal></entry></row>
2634 <row><entry><literal><![CDATA[--]]></literal></entry><entry><literal><![CDATA[post_increment_decrement_action<decrement_action>]]></literal></entry></row>
2635
2636
2637
2638 <row><entry><literal><![CDATA[&]]></literal></entry><entry><literal><![CDATA[other_action<address_of_action>]]></literal></entry></row>
2639 <row><entry><literal><![CDATA[*]]></literal></entry><entry><literal><![CDATA[other_action<contents_of_action>]]></literal></entry></row>
2640 <row><entry><literal><![CDATA[,]]></literal></entry><entry><literal><![CDATA[other_action<comma_action>]]></literal></entry></row>
2641
2642 </tbody>
2643 </tgroup>
2644 </table>
2645
2646 </section>
2647
2648
2649 <section>
2650 <title>Practical considerations</title>
2651
2652
2653 <section>
2654 <title>Performance</title>
2655
2656 <para>In theory, all overhead of using STL algorithms and lambda functors 
2657 compared to hand written loops can be optimized away, just as the overhead 
2658 from standard STL function objects and binders can.
2659
2660 Depending on the compiler, this can also be true in practice.
2661 We ran two tests with the GCC 3.0.4 compiler on 1.5 GHz Intel Pentium 4.
2662 The optimization flag -03 was used.
2663 </para>
2664
2665 <para>
2666 In the first test we compared lambda functors against explicitly written 
2667 function objects. 
2668 We used both of these styles to define unary functions which multiply the
2669 argument repeatedly by itself. 
2670 We started with the identity function, going up to 
2671 x<superscript>5</superscript>.
2672 The expressions were called inside a <literal>std::transform</literal> loop, 
2673 reading the argument from one <literal><![CDATA[std::vector<int>]]></literal> 
2674 and placing the result into another.
2675 The length of the vectors was 100 elements.
2676 The running times are listed in 
2677 <xref linkend="table:increasing_arithmetic_test"/>.
2678
2679 We can observe that there is no significant difference between the
2680 two approaches.
2681 </para>
2682
2683 <para>
2684 In the second test we again used <literal>std::transform</literal> to 
2685 perform an operation to each element in a 100-element long vector.
2686 This time the element type of the vectors was <literal>double</literal>
2687 and we started with very simple arithmetic expressions and moved to 
2688 more complex ones.
2689 The running times are listed in <xref linkend="table:ll_vs_stl_test"/>.
2690
2691 Here, we also included classic STL style unnamed functions into tests.
2692 We do not show these expressions, as they get rather complex. 
2693 For example, the
2694 last expression in <xref linkend="table:ll_vs_stl_test"/> written with
2695 classic STL tools contains 7 calls to <literal>compose2</literal>, 
2696 8 calls to <literal>bind1st</literal>
2697 and altogether 14 constructor invocations for creating 
2698 <literal>multiplies</literal>, <literal>minus</literal> 
2699 and <literal>plus</literal> objects.
2700
2701 In this test the BLL expressions are a little slower (roughly 10% on average,
2702 less than 14% in all cases)
2703 than the corresponding hand-written function objects.
2704 The performance hit is a bit greater with classic STL expressions,
2705 up to 27% for the simplest expressios.
2706 </para>
2707
2708 <para>
2709 The tests suggest that the BLL does not introduce a loss of performance 
2710 compared to STL function objects.  
2711 With a reasonable optimizing compiler, one should expect the performance characteristics be comparable to using classic STL.
2712 Moreover, with simple expressions the performance can be expected to be close
2713 to that of explicitly written function objects.
2714
2715 <!-- We repeated both tests with the KAI C++ 4.0f compiler (using +K2 -O3 flags), 
2716 generally considered a good optimizing compiler.
2717 We do not list the results here, since the running times for the two alternatives in the first test were essentially the same, just as the running times
2718 for the three different alternatives in the second test.
2719 These tests suggest there to be no performance penalty at all
2720 with a good optimizing compiler.
2721 -->
2722
2723 Note however, that evaluating a lambda functor consist of a sequence of calls to small functions that are declared inline. 
2724 If the compiler fails to actually expand these functions inline, 
2725 the performance can suffer. 
2726 The running time can more than double if this happens.
2727 Although the above tests do not include such an expression, we have experienced
2728 this for some seemingly simple expressions.
2729
2730
2731 <table id = "table:increasing_arithmetic_test">
2732 <title>Test 1. CPU time of expressions with integer multiplication written as a lambda expression and as a traditional hand-coded function object class. 
2733 The running times are expressed in arbitrary units.</title>
2734 <tgroup cols="3">
2735 <thead>
2736 <row>
2737 <entry>expression</entry><entry>lambda expression</entry><entry>hand-coded function object</entry></row>
2738 </thead>
2739
2740 <tbody>
2741
2742 <row>
2743 <entry>x</entry><entry>240</entry><entry>230</entry>
2744 </row>
2745
2746 <row>
2747 <entry>x*x</entry><entry>340</entry><entry>350</entry>
2748 </row>
2749
2750 <row>
2751 <entry>x*x*x</entry><entry>770</entry><entry>760</entry>
2752 </row>
2753
2754 <row>
2755 <entry>x*x*x*x</entry><entry>1180</entry><entry>1210</entry>
2756 </row>
2757
2758 <row>
2759 <entry>x*x*x*x*x</entry><entry>1950</entry><entry>1910</entry>
2760 </row>
2761
2762 </tbody>
2763 </tgroup>
2764 </table>
2765 </para>
2766
2767 <!--
2768 16:19:49 bench [601] ./arith.out 100 1000000
2769
2770 Number of elements = 100
2771 L1 : 240
2772 L2 : 340
2773 L3 : 770
2774 L4 : 1180
2775 L5 : 1950
2776
2777 P2 : 1700
2778 P3 : 2130
2779 P4 : 2530
2780 P5 : 3000
2781
2782 F1 : 230
2783 F2 : 350
2784 F3 : 760
2785 F4 : 1210
2786 F5 : 1910
2787
2788
2789 Number of elements    = 100
2790 Number of outer_iters = 1000000
2791 L1 : 330
2792 L2 : 350
2793 L3 : 470
2794 L4 : 620
2795 L5 : 1660
2796 LP : 1230
2797 C1 : 370
2798 C2 : 370
2799 C3 : 500
2800 C4 : 670
2801 C5 : 1660
2802 CP : 1770
2803 F1 : 290
2804 F2 : 310
2805 F3 : 420
2806 F4 : 600
2807 F5 : 1460
2808 FP : 1040
2809
2810 -->
2811
2812
2813 <para>
2814 <table id = "table:ll_vs_stl_test">
2815 <title>Test 2. CPU time of arithmetic expressions written as lambda 
2816 expressions, as classic STL unnamed functions (using <literal>compose2</literal>, <literal>bind1st</literal> etc.) and as traditional hand-coded function object classes. 
2817 Using BLL terminology, 
2818 <literal>a</literal> and <literal>b</literal> are bound arguments in the expressions, and <literal>x</literal> is open. 
2819 All variables were of types <literal>double</literal>.
2820 The running times are expressed in arbitrary units.</title>
2821 <tgroup cols="4">
2822 <thead>
2823 <row>
2824 <entry>expression</entry><entry>lambda expression</entry><entry>classic STL expression</entry><entry>hand-coded function object</entry></row>
2825 </thead>
2826
2827 <tbody>
2828
2829 <row>
2830 <entry>ax</entry><entry>330</entry><entry>370</entry><entry>290</entry>
2831 </row>
2832
2833 <row>
2834 <entry>-ax</entry><entry>350</entry><entry>370</entry><entry>310</entry>
2835 </row>
2836
2837 <row>
2838 <entry>ax-(a+x)</entry><entry>470</entry><entry>500</entry><entry>420</entry>
2839 </row>
2840
2841 <row>
2842 <entry>(ax-(a+x))(a+x)</entry><entry>620</entry><entry>670</entry><entry>600</entry>
2843 </row>
2844
2845 <row>
2846 <entry>((ax) - (a+x))(bx - (b+x))(ax - (b+x))(bx - (a+x))</entry><entry>1660</entry><entry>1660</entry><entry>1460</entry>
2847 </row>
2848
2849 </tbody>
2850 </tgroup>
2851
2852 </table>
2853 </para>
2854
2855
2856 <para>Some additional performance testing with an earlier version of the
2857 library is described
2858 <xref linkend="cit:jarvi:00"/>.
2859 </para>
2860
2861 </section>
2862     <section>
2863       <title>About compiling</title>
2864
2865       <para>The BLL uses templates rather heavily, performing numerous recursive instantiations of the same templates. 
2866 This has (at least) three implications:
2867 <itemizedlist>
2868
2869 <listitem>
2870 <para>
2871 While it is possible to write incredibly complex lambda expressions, it probably isn't a good idea. 
2872 Compiling such expressions may end up requiring a lot of memory 
2873 at compile time, and being slow to compile.
2874 </para>
2875 </listitem>
2876
2877
2878 <listitem>
2879 <para>
2880 The types of lambda functors that result from even the simplest lambda expressions are cryptic. 
2881 Usually the programmer doesn't need to deal with the lambda functor types at all, but in the case of an error in a lambda expression, the compiler usually outputs the types of the lambda functors involved. 
2882 This can make the error messages very long and difficult to interpret, particularly if the compiler outputs the whole chain of template instantiations.
2883 </para>
2884 </listitem>
2885
2886 <listitem>
2887 <para>
2888 The C++ Standard suggests a template nesting level of 17 to help detect infinite recursion. 
2889 Complex lambda templates can easily exceed this limit. 
2890 Most compilers allow a greater number of nested templates, but commonly require the limit explicitly increased with a command line argument.
2891 </para>
2892 </listitem>
2893 </itemizedlist></para>
2894
2895     </section>
2896
2897     <section>
2898       <title>Portability</title>
2899       <para>
2900 The BLL works with the following compilers, that is, the compilers are capable of compiling the test cases that are included with the BLL:
2901
2902       <itemizedlist>
2903         <listitem>GCC 3.0.4
2904         </listitem>
2905         <listitem>KCC 4.0f with EDG 2.43.1
2906         </listitem>
2907         <listitem>GCC 2.96 (fails with one test case, the <filename>exception_test.cpp</filename> results in an internal compiler error.
2908 )
2909
2910         </listitem>
2911       </itemizedlist>
2912 </para>
2913
2914       <section>
2915         <title>Test coverage</title>
2916
2917 <para>The following list describes the test files included and the features that each file covers:
2918
2919 <itemizedlist>
2920 <listitem>
2921 <para>
2922 <filename>bind_tests_simple.cpp</filename> : Bind expressions of different arities and types of target functions: function pointers, function objects and member functions.
2923 Function composition with bind expressions.</para>
2924 </listitem>
2925
2926 <listitem>
2927 <para><filename>bind_tests_simple_function_references.cpp</filename> :
2928 Repeats all tests from <filename moreinfo="none">bind_tests_simple.cpp</filename> where the target function is a function pointer, but uses function references instead.
2929 </para></listitem>
2930
2931             
2932 <listitem>
2933 <para><filename>bind_tests_advanced.cpp</filename> : Contains tests for nested bind expressions, <literal>unlambda</literal>, <literal>protect</literal>, <literal>const_parameters</literal> and <literal>break_const</literal>.
2934 Tests passing lambda functors as actual arguments to other lambda functors, currying, and using the <literal>sig</literal> template to specify the return type of a function object.
2935 </para>
2936 </listitem>
2937
2938 <listitem>
2939 <para>
2940 <filename>operator_tests_simple.cpp</filename> :
2941 Tests using all operators that are overloaded for lambda expressions, that is, unary and binary arithmetic, 
2942 bitwise, 
2943 comparison, 
2944 logical,
2945 increment and decrement, 
2946 compound, 
2947 assignment,
2948 subscrict, 
2949 address of,
2950 dereference, and comma operators.
2951 The streaming nature of shift operators is tested, as well as pointer arithmetic with plus and minus operators.
2952 </para>
2953 </listitem>
2954             
2955 <listitem>
2956 <para><filename>member_pointer_test.cpp</filename> : The pointer to member operator is complex enough to warrant a separate test file.
2957 </para>
2958 </listitem>
2959
2960 <listitem>
2961 <para>
2962 <filename>control_structures.cpp</filename> :
2963 Tests for the looping and if constructs.
2964 </para></listitem>
2965
2966 <listitem>
2967 <para>
2968 <filename>switch_construct.cpp</filename> :
2969 Includes tests for all supported arities of the switch statement, both with and without the default case.
2970 </para>
2971 </listitem>
2972
2973 <listitem>
2974 <para>
2975 <filename>exception_test.cpp</filename> :
2976 Includes tests for throwing exceptions and for try/catch constructs with varying number of catch blocks.
2977 </para>
2978 </listitem>
2979
2980 <listitem>
2981 <para>
2982 <filename>constructor_tests.cpp</filename> :
2983 Contains tests for <literal>constructor</literal>, <literal>destructor</literal>, <literal>new_ptr</literal>, <literal>delete_ptr</literal>, <literal>new_array</literal> and <literal>delete_array</literal>.
2984 </para>
2985 </listitem>
2986
2987 <listitem>
2988 <para>
2989 <filename>cast_test.cpp</filename> : Tests for the four cast expressions, as well as <filename>typeid</filename> and <literal>sizeof</literal>.
2990 </para>
2991 </listitem>
2992
2993 <listitem>
2994 <para>
2995 <filename>extending_return_type_traits.cpp</filename> : Tests extending the return type deduction system for user defined types.
2996 Contains several user defined operators and the corresponding specializations for the return type deduction templates.
2997 </para>
2998 </listitem>
2999
3000 <listitem>
3001 <para>
3002 <filename>is_instance_of_test.cpp</filename> : Includes tests for an internally used traits template, which can detect whether a given type is an instance of a certain template or not. 
3003 </para></listitem>
3004
3005 <listitem>
3006 <para>
3007 <filename>bll_and_function.cpp</filename> :
3008 Contains tests for using <literal>boost::function</literal> together with lambda functors.
3009 </para></listitem>
3010
3011           </itemizedlist>
3012
3013 </para>
3014
3015       </section>
3016
3017     </section>
3018
3019
3020 </section>
3021
3022
3023 <section>
3024 <title>Relation to other Boost libraries</title>
3025
3026 <section>
3027 <title>Boost Function</title>
3028
3029 <para>Sometimes it is convenient to store lambda functors in variables.
3030 However, the types of even the simplest lambda functors are long and unwieldy, and it is in general unfeasible to declare variables with lambda functor types.
3031 <emphasis>The Boost Function library</emphasis> <xref linkend="cit:boost::function"/> defines wrappers for arbitrary function objects, for example 
3032 lambda functors; and these wrappers have types that are easy to type out.
3033
3034 For example:
3035
3036 <programlisting>
3037 <![CDATA[boost::function<int(int, int)> f = _1 + _2;
3038 boost::function<int&(int&)> g = (_1 += 10);
3039 int i = 1, j = 2;
3040 f(i, j); // returns 3
3041 g(i);    // sets i to = 11;]]>
3042 </programlisting>
3043
3044 The return and parameter types of the wrapped function object must be written explicilty as the template argument to the wrapper template <literal>boost::function</literal>; even when lambda functors, which otherwise have generic parameters, are wrapped.
3045 Wrapping a function object with <literal>boost::function</literal> introduces a performance cost comparable to virtual function dispatch, though virtual functions are not actually used.
3046
3047 Note that storing lambda functors inside <literal>boost::function</literal> 
3048 introduces a danger.
3049 Certain types of lambda functors may store references to the bound 
3050 arguments, instead as taking copies of the arguments of the lambda expression.
3051 When temporary lambda functor objects are used 
3052 in STL algorithm invocations this is always safe, as the lambda functor gets 
3053 destructed immediately after the STL algortihm invocation is completed.
3054
3055 However, a lambda functor wrapped inside <literal>boost::function</literal> 
3056 may continue to exist longer, creating the possibility of dangling references.
3057 For example:
3058
3059 <programlisting>
3060 <![CDATA[int* sum = new int();
3061 *sum = 0;
3062 boost::function<int&(int)> counter = *sum += _1;
3063 counter(5); // ok, *sum = 5;
3064 delete sum; 
3065 counter(3); // error, *sum does not exist anymore]]>
3066 </programlisting>
3067
3068 </para>
3069
3070 </section>
3071
3072 <section>
3073 <title>Boost Bind</title>
3074 <para>
3075 <emphasis>The Boost Bind</emphasis> <xref linkend="cit:boost::bind"/> library has partially overlapping functionality with the BLL. 
3076 Basically, the Boost Bind library (BB in the sequel) implements the bind expression part of BLL.
3077 There are, however, some semantical differerences.
3078 </para>
3079 <para>
3080 The BLL and BB evolved separately, and have different implementations. 
3081 This means that the bind expressions from the BB cannot be used within 
3082 bind expressions, or within other type of lambda expressions, of the BLL.
3083 The same holds for using BLL bind expressions in the BB.
3084 The libraries can coexist, however, as
3085 the names of the BB library are in <literal>boost</literal> namespace, 
3086 whereas the BLL names are in <literal>boost::lambda</literal> namespace.
3087 </para>
3088
3089 <para>
3090 The BLL requires a compiler that is reasonably conformant to the 
3091 C++ standard, whereas the BB library is more portable, and works with 
3092 a larger set of compilers. 
3093 </para>
3094
3095 <para>
3096 The following two sections describe what are the semantic differences 
3097 between the bind expressions in BB and BLL.
3098 </para>
3099
3100
3101
3102
3103 <section>
3104 <title>First argument of bind expression</title>
3105
3106 In BB the first argument of the bind expression, the target function, 
3107 is treated differently from the other arguments, 
3108 as no argument substitution takes place within that argument.
3109 In BLL the first argument is not a special case in this respect.
3110
3111 For example:
3112
3113 <programlisting>
3114 <![CDATA[template<class F>
3115 int foo(const F& f) {
3116   int x;
3117   ..
3118   bind(f, _1)(x);
3119   ...
3120 }]]>
3121 </programlisting>
3122
3123 <programlisting>
3124 <![CDATA[int bar(int, int);
3125 nested(bind(bar, 1, _1));]]>
3126 </programlisting>
3127
3128 The bind expression inside <literal>foo</literal> becomes:
3129 <programlisting>
3130 bind(bind(bar, 1, _1), _1)(x)
3131 </programlisting>
3132
3133 The BLL interpretes this as:
3134 <programlisting>
3135 bar(1, x)(x)
3136 </programlisting>
3137 whereas the BB library as
3138 <programlisting>
3139 bar(1, x)
3140 </programlisting>
3141
3142 To get this functionality in BLL, the bind expression inside the <literal moreinfo="none">foo</literal> function can be written as:
3143 <programlisting>
3144 bind(unlambda(f), _1)(x);
3145 </programlisting>
3146 as explained in <xref linkend = "sect:unlambda"/>. 
3147
3148 </section>
3149
3150
3151
3152
3153 <para>
3154 The BB library supports up to nine placeholders, while the BLL 
3155 defines only three placeholders. 
3156 The rationale for not providing more, is that the highest arity of the
3157 function objects accepted by any STL algorithm is two. 
3158 The placeholder count is easy to increase in the BB library.
3159 In BLL it is possible, but more laborous.
3160 The BLL currently passes the actual arguments to the lambda functors
3161 internally just as they are and does not wrap them inside a tuple object.
3162 The reason for this is that some widely used compilers are not capable
3163 of optimizing the intermediate tuple objects away. 
3164 The creation of the intermediate tuples would cause a significant
3165 performance hit, particularly for the simplest (and thus the most common) 
3166 lambda functors.  
3167 We are working on a hybrid approach, which will allow more placeholders
3168 but not compromise the performance of simple lambda functors.
3169 </para>
3170
3171 </section>
3172
3173   </section>
3174
3175
3176 <section>
3177 <title>Contributors</title>
3178
3179 The main body of the library was written by Jaakko Järvi and Gary Powell.
3180 We've got outside help, suggestions and ideas from Jeremy Siek, Peter Higley, Peter Dimov, Valentin Bonnard, William Kempf.
3181 We would particularly like to mention Joel de Guzmann and his work with 
3182 Phoenix which has influenced BLL significantly, making it considerably simpler 
3183 to extend the library with new features.
3184
3185 </section>
3186
3187
3188
3189 <appendix>
3190 <title>Rationale for some of the design decisions</title>
3191
3192 <section id="sect:why_weak_arity">
3193 <title>
3194 Lambda functor arity
3195 </title>
3196
3197 <para>
3198 The highest placeholder index in a lambda expression determines the arity of the resulting function object.
3199 However, this is just the minimal arity, as the function object can take arbitrarily many arguments; those not needed are discarded.
3200 Consider the two bind expressions and their invocations below:
3201
3202 <programlisting>
3203 bind(g, _3, _3, _3)(x, y, z); 
3204 bind(g, _1, _1, _1)(x, y, z); 
3205 </programlisting>
3206
3207 This first line discards arguments <literal>x</literal> and
3208 <literal>y</literal>, and makes the call:
3209 <programlisting>
3210 g(z, z, z) 
3211 </programlisting>
3212 whereas the second line discards arguments <literal>y</literal> and
3213 <literal>z</literal>, and calls:
3214 <programlisting>
3215 g(x, x, x)
3216 </programlisting>
3217 In earlier versions of the library, the latter line resulted in a compile 
3218 time error.
3219
3220 This is basically a tradeoff between safety and flexibility, and the issue
3221 was extensively discussed during the Boost review period of the library.
3222 The main points for the <emphasis>strict arity</emphasis> checking
3223 was that it might
3224 catch a programming error at an earlier time and that a lambda expression that
3225 explicitly discards its arguments is easy to write:
3226 <programlisting>
3227 (_3, bind(g, _1, _1, _1))(x, y, z);
3228 </programlisting>
3229 This lambda expression takes three arguments.
3230 The left-hand argument of the comma operator does nothing, and as comma 
3231 returns the result of evaluating the right-hand argument we end up with 
3232 the call
3233 <literal>g(x, x, x)</literal>
3234 even with the strict arity.
3235 </para>
3236
3237 <para>
3238 The main points against the strict arity checking were that the need to 
3239 discard arguments is commonplace, and should therefore be straightforward, 
3240 and that strict arity checking does not really buy that much more safety, 
3241 particularly as it is not symmetric.
3242 For example, if the programmer wanted to write the expression 
3243 <literal>_1 + _2</literal> but mistakenly wrote <literal>_1 + 2</literal>, 
3244 with strict arity checking, the complier would spot the error.
3245 However, if the erroneous expression was <literal>1 + _2</literal> instead,
3246 the error would go unnoticed.
3247 Furthermore, weak arity checking simplifies the implementation a bit.
3248 Following the recommendation of the Boost review, strict arity checking 
3249 was dropped.
3250 </para>
3251
3252 </section>
3253
3254 </appendix>
3255
3256
3257
3258 <bibliography>
3259
3260 <biblioentry id="cit:stepanov:94">
3261 <abbrev>STL94</abbrev>
3262 <authorgroup>
3263 <author>
3264 <surname>Stepanov</surname>
3265 <firstname>A. A.</firstname>
3266 </author>
3267 <author>
3268 <surname>Lee</surname>
3269 <firstname>M.</firstname>
3270 </author>
3271 </authorgroup>      
3272 <title>The Standard Template Library</title>
3273 <orgname>Hewlett-Packard Laboratories</orgname>
3274 <pubdate>1994</pubdate>
3275 <bibliomisc>
3276 <ulink url="http://www.hpl.hp.com/techreports">www.hpl.hp.com/techreports</ulink>
3277 </bibliomisc>
3278 </biblioentry>
3279
3280 <biblioentry id="cit:sgi:02">
3281 <abbrev>SGI02</abbrev>
3282 <title>The SGI Standard Template Library</title>
3283 <pubdate>2002</pubdate>
3284 <bibliomisc><ulink url="http://www.sgi.com/tech/stl/">www.sgi.com/tech/stl/</ulink></bibliomisc>
3285
3286 </biblioentry>
3287     
3288 <biblioentry id="cit:c++:98">
3289 <abbrev>C++98</abbrev>
3290 <title>International Standard, Programming Languages &ndash; C++</title>
3291 <subtitle>ISO/IEC:14882</subtitle>
3292 <pubdate>1998</pubdate>
3293 </biblioentry>
3294
3295
3296 <biblioentry id="cit:jarvi:99">
3297 <abbrev>Jär99</abbrev>
3298
3299 <articleinfo>
3300 <author>
3301 <surname>Järvi</surname>
3302 <firstname>Jaakko</firstname>
3303 </author>
3304 <title>C++ Function Object Binders Made Easy</title>
3305 </articleinfo>
3306
3307 <title>Lecture Notes in Computer Science</title>
3308 <volumenum>1977</volumenum>
3309 <publishername>Springer</publishername>
3310
3311 <pubdate>2000</pubdate>
3312 </biblioentry>
3313
3314
3315
3316 <biblioentry id="cit:jarvi:00">
3317 <abbrev>Jär00</abbrev>
3318 <author>
3319 <surname>Järvi</surname>
3320 <firstname>Jaakko</firstname>
3321 </author>
3322 <author>
3323 <firstname>Gary</firstname>
3324 <surname>Powell</surname>
3325 </author>
3326 <title>The Lambda Library : Lambda Abstraction in C++</title>
3327       <orgname>Turku Centre for Computer Science</orgname>
3328 <bibliomisc>Technical Report </bibliomisc>
3329       <issuenum>378</issuenum>
3330 <pubdate>2000</pubdate>
3331 <bibliomisc><ulink url="http://www.tucs.fi/Publications/techreports/TR378.php">www.tucs.fi/publications</ulink></bibliomisc>
3332
3333
3334 </biblioentry>
3335
3336
3337 <biblioentry id="cit:jarvi:01">
3338 <abbrev>Jär01</abbrev>
3339 <author>
3340 <surname>Järvi</surname>
3341 <firstname>Jaakko</firstname>
3342 </author>
3343 <author>
3344 <firstname>Gary</firstname>
3345 <surname>Powell</surname>
3346 </author>
3347 <title>The Lambda Library : Lambda Abstraction in C++</title>
3348       <confgroup>
3349         <conftitle>Second  Workshop on C++ Template Programming</conftitle>
3350         <address>Tampa Bay, OOPSLA'01</address>
3351       </confgroup>
3352 <pubdate>2001</pubdate>
3353 <bibliomisc><ulink url="http://www.oonumerics.org/tmpw01/">www.oonumerics.org/tmpw01/</ulink></bibliomisc>
3354 </biblioentry>
3355
3356 <biblioentry id="cit:jarvi:03">
3357 <abbrev>Jär03</abbrev>
3358
3359 <articleinfo>
3360
3361 <author>
3362 <surname>Järvi</surname>
3363 <firstname>Jaakko</firstname>
3364 </author>
3365
3366 <author>
3367 <firstname>Gary</firstname>
3368 <surname>Powell</surname>
3369 </author>
3370
3371 <author>
3372 <firstname>Andrew</firstname>
3373 <surname>Lumsdaine</surname>
3374 </author>
3375 <title>The Lambda Library : unnamed functions in C++</title>
3376
3377 </articleinfo>
3378
3379 <title>Software - Practice and Expreience</title>
3380 <volumenum>33:259-291</volumenum>
3381
3382
3383 <pubdate>2003</pubdate>
3384 </biblioentry>
3385
3386
3387 <biblioentry id="cit:boost::tuple">
3388 <abbrev>tuple</abbrev>
3389 <title>The Boost Tuple Library</title>
3390 <bibliomisc><ulink url="http://www.boost.org/libs/tuple/doc/tuple_users_guide.html">www.boost.org/libs/tuple/doc/tuple_users_guide.html</ulink>
3391 </bibliomisc>
3392 <pubdate>2002</pubdate>
3393 </biblioentry>
3394
3395 <biblioentry id="cit:boost::type_traits">
3396 <abbrev>type_traits</abbrev>
3397 <title>The Boost type_traits</title>
3398 <bibliomisc><ulink url="http://www.boost.org/libs/type_traits/index.htm">www.boost.org/libs/type_traits/</ulink>
3399 </bibliomisc>
3400 <pubdate>2002</pubdate>
3401 </biblioentry>
3402
3403 <biblioentry id="cit:boost::ref">
3404 <abbrev>ref</abbrev>
3405 <title>Boost ref</title>
3406 <bibliomisc><ulink url="http://www.boost.org/libs/bind/ref.html">www.boost.org/libs/bind/ref.html</ulink>
3407 </bibliomisc>
3408 <pubdate>2002</pubdate>
3409 </biblioentry>
3410
3411 <biblioentry id="cit:boost::bind">
3412 <abbrev>bind</abbrev>
3413 <title>Boost Bind Library</title>
3414 <bibliomisc><ulink url="http://www.boost.org/libs/bind/bind.html">www.boost.org/libs/bind/bind.html</ulink>
3415 </bibliomisc>
3416 <pubdate>2002</pubdate>
3417 </biblioentry>
3418
3419 <biblioentry id="cit:boost::function">
3420 <abbrev>function</abbrev>
3421 <title>Boost Function Library</title>
3422 <bibliomisc><ulink url="http://www.boost.org/libs/function/">www.boost.org/libs/function/</ulink>
3423 </bibliomisc>
3424 <pubdate>2002</pubdate>
3425 </biblioentry>
3426
3427 <biblioentry id="cit:fc++">
3428 <abbrev>fc++</abbrev>
3429 <title>The FC++ library: Functional Programming in C++</title>
3430 <author>
3431 <surname>Smaragdakis</surname>
3432 <firstname>Yannis</firstname>
3433 </author>
3434 <author>
3435 <firstname>Brian</firstname>
3436 <surname>McNamara</surname>
3437 </author>
3438 <bibliomisc><ulink url="http://www.cc.gatech.edu/~yannis/fc++/">www.cc.gatech.edu/~yannis/fc++/</ulink>
3439 </bibliomisc>
3440 <pubdate>2002</pubdate>
3441 </biblioentry>
3442
3443
3444
3445
3446 </bibliography>
3447
3448
3449
3450 </library>
3451
3452
3453
3454
3455
3456