lambda.xml 118 KB

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