Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/doc/html/lambda/using_library.html @ 66

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

updated boost from 1_33_1 to 1_34_1

File size: 15.3 KB
Line 
1<html>
2<head>
3<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4<title>Using the library</title>
5<link rel="stylesheet" href="../boostbook.css" type="text/css">
6<meta name="generator" content="DocBook XSL Stylesheets V1.68.1">
7<link rel="start" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
8<link rel="up" href="../lambda.html" title="Chapter 8. Boost.Lambda">
9<link rel="prev" href="s03.html" title="Introduction">
10<link rel="next" href="le_in_details.html" title="Lambda expressions in details">
11</head>
12<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
13<table cellpadding="2" width="100%">
14<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td>
15<td align="center"><a href="../../../index.htm">Home</a></td>
16<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td>
17<td align="center"><a href="../../../people/people.htm">People</a></td>
18<td align="center"><a href="../../../more/faq.htm">FAQ</a></td>
19<td align="center"><a href="../../../more/index.htm">More</a></td>
20</table>
21<hr>
22<div class="spirit-nav">
23<a accesskey="p" href="s03.html"><img src="../images/prev.png" alt="Prev"></a><a accesskey="u" href="../lambda.html"><img src="../images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../images/home.png" alt="Home"></a><a accesskey="n" href="le_in_details.html"><img src="../images/next.png" alt="Next"></a>
24</div>
25<div class="section" lang="en">
26<div class="titlepage"><div><div><h2 class="title" style="clear: both">
27<a name="lambda.using_library"></a>Using the library</h2></div></div></div>
28<div class="toc"><dl>
29<dt><span class="section"><a href="using_library.html#lambda.introductory_examples">Introductory Examples</a></span></dt>
30<dt><span class="section"><a href="using_library.html#lambda.parameter_and_return_types">Parameter and return types of lambda functors</a></span></dt>
31<dt><span class="section"><a href="using_library.html#lambda.actual_arguments_to_lambda_functors">About actual arguments to lambda functors</a></span></dt>
32<dt><span class="section"><a href="using_library.html#lambda.storing_bound_arguments">Storing bound arguments in lambda functions</a></span></dt>
33</dl></div>
34<p>
35The purpose of this section is to introduce the basic functionality of the library.
36There are quite a lot of exceptions and special cases, but discussion of them is postponed until later sections.
37
38
39    </p>
40<div class="section" lang="en">
41<div class="titlepage"><div><div><h3 class="title">
42<a name="lambda.introductory_examples"></a>Introductory Examples</h3></div></div></div>
43<p>
44        In this section we give basic examples of using BLL lambda expressions in STL algorithm invocations.
45        We start with some simple expressions and work up.
46        First, we initialize the elements of a container, say, a <code class="literal">list</code>, to the value <code class="literal">1</code>:
47
48
49        </p>
50<pre class="programlisting">
51list&lt;int&gt; v(10);
52for_each(v.begin(), v.end(), _1 = 1);</pre>
53<p>
54
55        The expression <code class="literal">_1 = 1</code> creates a lambda functor which assigns the value <code class="literal">1</code> to every element in <code class="literal">v</code>.<sup>[<a name="id1243857" href="#ftn.id1243857">1</a>]</sup>
56      </p>
57<p>
58        Next, we create a container of pointers and make them point to the elements in the first container <code class="literal">v</code>:
59
60        </p>
61<pre class="programlisting">
62vector&lt;int*&gt; vp(10);
63transform(v.begin(), v.end(), vp.begin(), &amp;_1);</pre>
64<p>
65
66The expression <code class="literal">&amp;_1</code> creates a function object for getting the address of each element in <code class="literal">v</code>.
67The addresses get assigned to the corresponding elements in <code class="literal">vp</code>.
68      </p>
69<p>
70        The next code fragment changes the values in <code class="literal">v</code>.
71        For each element, the function <code class="literal">foo</code> is called.
72The original value of the element is passed as an argument to <code class="literal">foo</code>.
73The result of <code class="literal">foo</code> is assigned back to the element:
74
75
76        </p>
77<pre class="programlisting">
78int foo(int);
79for_each(v.begin(), v.end(), _1 = bind(foo, _1));</pre>
80<p>
81      </p>
82<p>
83        The next step is to sort the elements of <code class="literal">vp</code>:
84       
85        </p>
86<pre class="programlisting">sort(vp.begin(), vp.end(), *_1 &gt; *_2);</pre>
87<p>
88
89        In this call to <code class="literal">sort</code>, we are sorting the elements by their contents in descending order.
90      </p>
91<p>
92        Finally, the following <code class="literal">for_each</code> call outputs the sorted content of <code class="literal">vp</code> separated by line breaks:
93
94</p>
95<pre class="programlisting">
96for_each(vp.begin(), vp.end(), cout &lt;&lt; *_1 &lt;&lt; '\n');
97</pre>
98<p>
99
100Note that a normal (non-lambda) expression as subexpression of a lambda expression is evaluated immediately. 
101This may cause surprises.
102For instance, if the previous example is rewritten as
103</p>
104<pre class="programlisting">
105for_each(vp.begin(), vp.end(), cout &lt;&lt; '\n' &lt;&lt; *_1);
106</pre>
107<p>
108the subexpression <code class="literal">cout &lt;&lt; '\n'</code> is evaluated immediately and the effect is to output a single line break, followed by the elements of <code class="literal">vp</code>.
109The BLL provides functions <code class="literal">constant</code> and <code class="literal">var</code> to turn constants and, respectively, variables into lambda expressions, and can be used to prevent the immediate evaluation of subexpressions:
110</p>
111<pre class="programlisting">
112for_each(vp.begin(), vp.end(), cout &lt;&lt; constant('\n') &lt;&lt; *_1);
113</pre>
114<p>
115These functions are described more thoroughly in <a href="le_in_details.html#lambda.delaying_constants_and_variables" title="Delaying constants and variables">the section called &#8220;Delaying constants and variables&#8221;</a>
116
117</p>
118</div>
119<div class="section" lang="en">
120<div class="titlepage"><div><div><h3 class="title">
121<a name="lambda.parameter_and_return_types"></a>Parameter and return types of lambda functors</h3></div></div></div>
122<p>
123        During the invocation of a lambda functor, the actual arguments are substituted for the placeholders.
124        The placeholders do not dictate the type of these actual arguments.
125        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.
126        As an example, the expression
127        <code class="literal">_1 + _2</code> creates a binary lambda functor.
128        It can be called with two objects of any types <code class="literal">A</code> and <code class="literal">B</code> for which <code class="literal">operator+(A,B)</code> is defined (and for which BLL knows the return type of the operator, see below).
129      </p>
130<p>
131        C++ lacks a mechanism to query a type of an expression.
132        However, this precise mechanism is crucial for the implementation of C++ lambda expressions.
133        Consequently, BLL includes a somewhat complex type deduction system which uses a set of traits classes for deducing the resulting type of lambda functions.
134        It handles expressions where the operands are of built-in types and many of the expressions with operands of standard library types.
135        Many of the user defined types are covered as well, particularly if the user defined operators obey normal conventions in defining the return types.
136      </p>
137<p>
138        There are, however, cases when the return type cannot be deduced. For example, suppose you have defined:
139
140        </p>
141<pre class="programlisting">C operator+(A, B);</pre>
142<p>
143
144        The following lambda function invocation fails, since the return type cannot be deduced:
145
146        </p>
147<pre class="programlisting">A a; B b; (_1 + _2)(a, b);</pre>
148<p>
149      </p>
150<p>
151        There are two alternative solutions to this.
152        The first is to extend the BLL type deduction system to cover your own types (see <a href="extending.html" title="Extending return type deduction system">the section called &#8220;Extending return type deduction system&#8221;</a>).
153        The second is to use a special lambda expression (<code class="literal">ret</code>) which defines the return type in place (see <a href="le_in_details.html#lambda.overriding_deduced_return_type" title="Overriding the deduced return type">the section called &#8220;Overriding the deduced return type&#8221;</a>):
154
155        </p>
156<pre class="programlisting">A a; B b; ret&lt;C&gt;(_1 + _2)(a, b);</pre>
157<p>
158      </p>
159<p>
160        For bind expressions, the return type can be defined as a template argument of the bind function as well:
161        </p>
162<pre class="programlisting">bind&lt;int&gt;(foo, _1, _2);</pre>
163<p>
164
165
166      </p>
167</div>
168<div class="section" lang="en">
169<div class="titlepage"><div><div><h3 class="title">
170<a name="lambda.actual_arguments_to_lambda_functors"></a>About actual arguments to lambda functors</h3></div></div></div>
171<p>A general restriction for the actual arguments is that they cannot be non-const rvalues.
172        For example:
173
174</p>
175<pre class="programlisting">
176int i = 1; int j = 2;
177(_1 + _2)(i, j); // ok
178(_1 + _2)(1, 2); // error (!)
179</pre>
180<p>
181
182        This restriction is not as bad as it may look.
183        Since the lambda functors are most often called inside STL-algorithms,
184        the arguments originate from dereferencing iterators and the dereferencing operators seldom return rvalues.
185        And for the cases where they do, there are workarounds discussed in
186<a href="le_in_details.html#lambda.rvalues_as_actual_arguments" title="Rvalues as actual arguments to lambda functors">the section called &#8220;Rvalues as actual arguments to lambda functors&#8221;</a>.
187
188
189      </p>
190</div>
191<div class="section" lang="en">
192<div class="titlepage"><div><div><h3 class="title">
193<a name="lambda.storing_bound_arguments"></a>Storing bound arguments in lambda functions</h3></div></div></div>
194<p>
195
196By default, temporary const copies of the bound arguments are stored
197in the lambda functor.
198
199This means that the value of a bound argument is fixed at the time of the
200creation of the lambda function and remains constant during the lifetime
201of the lambda function object.
202For example:
203</p>
204<pre class="programlisting">
205int i = 1;
206(_1 = 2, _1 + i)(i);
207</pre>
208<p>
209The comma operator is overloaded to combine lambda expressions into a sequence;
210the resulting unary lambda functor first assigns 2 to its argument,
211then adds the value of <code class="literal">i</code> to it.
212The value of the expression in the last line is 3, not 4.
213In other words, the lambda expression that is created is
214<code class="literal">lambda x.(x = 2, x + 1)</code> rather than
215<code class="literal">lambda x.(x = 2, x + i)</code>.
216     
217</p>
218<p>
219
220As said, this is the default behavior for which there are exceptions.
221The exact rules are as follows:
222
223</p>
224<div class="itemizedlist"><ul type="disc">
225<li>
226<p>
227
228The programmer can control the storing mechanism with <code class="literal">ref</code> 
229and <code class="literal">cref</code> wrappers [<a href="../lambda.html#cit:boost::ref" title="[ref]"><span class="abbrev">ref</span></a>].
230
231Wrapping an argument with <code class="literal">ref</code>, or <code class="literal">cref</code>,
232instructs the library to store the argument as a reference,
233or as a reference to const respectively.
234
235For example, if we rewrite the previous example and wrap the variable
236<code class="literal">i</code> with <code class="literal">ref</code>,
237we are creating the lambda expression <code class="literal">lambda x.(x = 2, x + i)</code> 
238and the value of the expression in the last line will be 4:
239
240</p>
241<pre class="programlisting">
242i = 1;
243(_1 = 2, _1 + ref(i))(i);
244</pre>
245<p>
246
247Note that <code class="literal">ref</code> and <code class="literal">cref</code> are different
248from <code class="literal">var</code> and <code class="literal">constant</code>.
249
250While the latter ones create lambda functors, the former do not.
251For example:
252
253</p>
254<pre class="programlisting">
255int i;
256var(i) = 1; // ok
257ref(i) = 1; // not ok, ref(i) is not a lambda functor
258</pre>
259<p>
260
261The functions <code class="literal">ref</code> and <code class="literal">cref</code> mostly
262exist for historical reasons,
263and <code class="literal">ref</code> can always
264be replaced with <code class="literal">var</code>, and <code class="literal">cref</code> with
265<code class="literal">constant_ref</code>.
266See <a href="le_in_details.html#lambda.delaying_constants_and_variables" title="Delaying constants and variables">the section called &#8220;Delaying constants and variables&#8221;</a> for details.
267The <code class="literal">ref</code> and <code class="literal">cref</code> functions are
268general purpose utility functions in Boost, and hence defined directly
269in the <code class="literal">boost</code> namespace.
270
271</p>
272</li>
273<li><p>
274Array types cannot be copied, they are thus stored as const reference by default.
275</p></li>
276<li>
277<p> 
278For some expressions it makes more sense to store the arguments as references.
279
280For example, the obvious intention of the lambda expression
281<code class="literal">i += _1</code> is that calls to the lambda functor affect the
282value of the variable <code class="literal">i</code>,
283rather than some temporary copy of it.
284
285As another example, the streaming operators take their leftmost argument
286as non-const references.
287
288The exact rules are:
289
290</p>
291<div class="itemizedlist"><ul type="circle">
292<li><p>The left argument of compound assignment operators (<code class="literal">+=</code>, <code class="literal">*=</code>, etc.) are stored as references to non-const.</p></li>
293<li><p>If the left argument of <code class="literal">&lt;&lt;</code> or <code class="literal">&gt;&gt;</code>  operator is derived from an instantiation of <code class="literal">basic_ostream</code> or respectively from <code class="literal">basic_istream</code>, the argument is stored as a reference to non-const.
294For all other types, the argument is stored as a copy.
295</p></li>
296<li><p>
297In pointer arithmetic expressions, non-const array types are stored as non-const references.
298This is to prevent pointer arithmetic making non-const arrays const.
299
300</p></li>
301</ul></div>
302<p>
303
304</p>
305</li>
306</ul></div>
307<p>
308</p>
309</div>
310<div class="footnotes">
311<br><hr width="100" align="left">
312<div class="footnote"><p><sup>[<a name="ftn.id1243857" href="#id1243857">1</a>] </sup>
313Strictly taken, the C++ standard defines <code class="literal">for_each</code> as a <span class="emphasis"><em>non-modifying sequence operation</em></span>, and the function object passed to <code class="literal">for_each</code> should not modify its argument.
314The requirements for the arguments of <code class="literal">for_each</code> are unnecessary strict, since as long as the iterators are <span class="emphasis"><em>mutable</em></span>, <code class="literal">for_each</code> accepts a function object that can have side-effects on their argument.
315Nevertheless, it is straightforward to provide another function template with the functionality of<code class="literal">std::for_each</code> but more fine-grained requirements for its arguments.
316</p></div>
317</div>
318</div>
319<table width="100%"><tr>
320<td align="left"></td>
321<td align="right"><small>Copyright © 1999-2004 Jaakko Järvi, Gary Powell</small></td>
322</tr></table>
323<hr>
324<div class="spirit-nav">
325<a accesskey="p" href="s03.html"><img src="../images/prev.png" alt="Prev"></a><a accesskey="u" href="../lambda.html"><img src="../images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../images/home.png" alt="Home"></a><a accesskey="n" href="le_in_details.html"><img src="../images/next.png" alt="Next"></a>
326</div>
327</body>
328</html>
Note: See TracBrowser for help on using the repository browser.