{"id":246,"date":"2017-05-11T18:18:02","date_gmt":"2017-05-11T18:18:02","guid":{"rendered":"http:\/\/imalogic.com\/blog\/?p=246"},"modified":"2017-05-12T12:42:08","modified_gmt":"2017-05-12T12:42:08","slug":"c11-why-lambdas-rock","status":"publish","type":"post","link":"https:\/\/imalogic.com\/blog\/2017\/05\/11\/c11-why-lambdas-rock\/","title":{"rendered":"C++11 &#8211; Why Lambdas Rock"},"content":{"rendered":"<body><p><\/p>\n<h2>The problem<\/h2>\n<p>C++ includes useful generic functions like <code>std::for_each<\/code> and <code>std::transform<\/code>, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the <a href=\"http:\/\/stackoverflow.com\/questions\/356950\/c-functors-and-their-uses\">functor<\/a> you would like to apply is unique to the particular function.<\/p>\n<pre class=\"lang-cpp prettyprint prettyprinted\"><code><span class=\"com\">#include<\/span> <span class=\"str\">&lt;algorithm&gt;<\/span>\r\n<span class=\"com\">#include<\/span> <span class=\"str\">&lt;vector&gt;<\/span>\r\n\r\n<span class=\"kwd\">namespace<\/span> <span class=\"pun\">{<\/span>\r\n  <span class=\"kwd\">struct<\/span><span class=\"pln\"> f <\/span><span class=\"pun\">{<\/span>\r\n    <span class=\"kwd\">void<\/span> <span class=\"kwd\">operator<\/span><span class=\"pun\">()(<\/span><span class=\"typ\">int<\/span><span class=\"pun\">)<\/span> <span class=\"pun\">{<\/span>\r\n      <span class=\"com\">\/\/ do something<\/span>\r\n    <span class=\"pun\">}<\/span>\r\n  <span class=\"pun\">};<\/span>\r\n<span class=\"pun\">}<\/span>\r\n\r\n<span class=\"kwd\">void<\/span><span class=\"pln\"> func<\/span><span class=\"pun\">(<\/span><span class=\"pln\">std<\/span><span class=\"pun\">::<\/span><span class=\"typ\">vector<\/span><span class=\"str\">&lt;int&gt;<\/span><span class=\"pun\">&amp;<\/span><span class=\"pln\"> v<\/span><span class=\"pun\">)<\/span> <span class=\"pun\">{<\/span><span class=\"pln\">\r\n  f f<\/span><span class=\"pun\">;<\/span><span class=\"pln\">\r\n  std<\/span><span class=\"pun\">::<\/span><span class=\"pln\">for_each<\/span><span class=\"pun\">(<\/span><span class=\"pln\">v<\/span><span class=\"pun\">.<\/span><span class=\"pln\">begin<\/span><span class=\"pun\">(),<\/span><span class=\"pln\"> v<\/span><span class=\"pun\">.<\/span><span class=\"pln\">end<\/span><span class=\"pun\">(),<\/span><span class=\"pln\"> f<\/span><span class=\"pun\">);<\/span>\r\n<span class=\"pun\">}<\/span><\/code><\/pre>\n<p>If you only use f once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off.<\/p>\n<p>In C++03 you might be tempted to write something like the following, to keep the functor local:<\/p>\n<pre class=\"lang-cpp prettyprint prettyprinted\"><code><span class=\"kwd\">void<\/span><span class=\"pln\"> func2<\/span><span class=\"pun\">(<\/span><span class=\"pln\">std<\/span><span class=\"pun\">::<\/span><span class=\"typ\">vector<\/span><span class=\"str\">&lt;int&gt;<\/span><span class=\"pun\">&amp;<\/span><span class=\"pln\"> v<\/span><span class=\"pun\">)<\/span> <span class=\"pun\">{<\/span>\r\n  <span class=\"kwd\">struct<\/span> <span class=\"pun\">{<\/span>\r\n    <span class=\"kwd\">void<\/span> <span class=\"kwd\">operator<\/span><span class=\"pun\">()(<\/span><span class=\"typ\">int<\/span><span class=\"pun\">)<\/span> <span class=\"pun\">{<\/span>\r\n       <span class=\"com\">\/\/ do something<\/span>\r\n    <span class=\"pun\">}<\/span>\r\n  <span class=\"pun\">}<\/span><span class=\"pln\"> f<\/span><span class=\"pun\">;<\/span><span class=\"pln\">\r\n  std<\/span><span class=\"pun\">::<\/span><span class=\"pln\">for_each<\/span><span class=\"pun\">(<\/span><span class=\"pln\">v<\/span><span class=\"pun\">.<\/span><span class=\"pln\">begin<\/span><span class=\"pun\">(),<\/span><span class=\"pln\"> v<\/span><span class=\"pun\">.<\/span><span class=\"pln\">end<\/span><span class=\"pun\">(),<\/span><span class=\"pln\"> f<\/span><span class=\"pun\">);<\/span>\r\n<span class=\"pun\">}<\/span><\/code><\/pre>\n<p>however this is not allowed, <code>f<\/code> cannot be passed to a template function in C++03.<\/p>\n<h2>The new solution<\/h2>\n<p>C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the <code>struct f<\/code>. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form:<\/p>\n<pre class=\"lang-cpp prettyprint prettyprinted\"><code><span class=\"kwd\">void<\/span><span class=\"pln\"> func3<\/span><span class=\"pun\">(<\/span><span class=\"pln\">std<\/span><span class=\"pun\">::<\/span><span class=\"typ\">vector<\/span><span class=\"str\">&lt;int&gt;<\/span><span class=\"pun\">&amp;<\/span><span class=\"pln\"> v<\/span><span class=\"pun\">)<\/span> <span class=\"pun\">{<\/span><span class=\"pln\">\r\n  std<\/span><span class=\"pun\">::<\/span><span class=\"pln\">for_each<\/span><span class=\"pun\">(<\/span><span class=\"pln\">v<\/span><span class=\"pun\">.<\/span><span class=\"pln\">begin<\/span><span class=\"pun\">(),<\/span><span class=\"pln\"> v<\/span><span class=\"pun\">.<\/span><span class=\"pln\">end<\/span><span class=\"pun\">(),<\/span> <span class=\"pun\">[](<\/span><span class=\"typ\">int<\/span><span class=\"pun\">)<\/span> <span class=\"pun\">{<\/span> <span class=\"com\">\/* do something here*\/<\/span> <span class=\"pun\">});<\/span>\r\n<span class=\"pun\">}<\/span><\/code><\/pre>\n<p>Lambda functions are just syntactic sugar for anonymous functors.<\/p>\n<h2>Basic Lambda Syntax<a href=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" data-attachment-id=\"271\" data-permalink=\"https:\/\/imalogic.com\/blog\/2017\/05\/11\/c11-why-lambdas-rock\/lambda\/\" data-orig-file=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda.png?fit=204%2C300&amp;ssl=1\" data-orig-size=\"204,300\" data-comments-opened=\"0\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"lambda\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda.png?fit=204%2C300&amp;ssl=1\" class=\"wp-image-271 alignright\" src=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda.png?resize=71%2C104&#038;ssl=1\" alt=\"\" width=\"71\" height=\"104\" loading=\"lazy\"><\/a><\/h2>\n<p>\u00a0<\/p>\n<p>Let\u2019s see the really basic syntax for lambda.<\/p>\n<p>\u00a0<\/p>\n<pre class=\"example\">#include &lt;iostream&gt;\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    auto func = [] () { cout &lt;&lt; \"Hello world\"; };\r\n    func(); \/\/ now call the function\r\n}<\/pre>\n<p>The identifier [ ], called the capture specification, tells the compiler we\u2019re creating a lambda function. You\u2019ll see this (or a variant) at the start of every lambda function.<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda_expression-1.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" data-attachment-id=\"248\" data-permalink=\"https:\/\/imalogic.com\/blog\/2017\/05\/11\/c11-why-lambdas-rock\/lambda_expression-2\/\" data-orig-file=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda_expression-1.png?fit=761%2C383&amp;ssl=1\" data-orig-size=\"761,383\" data-comments-opened=\"0\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"lambda_expression\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda_expression-1.png?fit=761%2C383&amp;ssl=1\" class=\"aligncenter wp-image-248 size-full\" src=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda_expression-1.png?resize=761%2C383&#038;ssl=1\" alt=\"\" width=\"761\" height=\"383\" loading=\"lazy\" srcset=\"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda_expression-1.png?w=761&amp;ssl=1 761w, https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda_expression-1.png?resize=300%2C151&amp;ssl=1 300w\" sizes=\"auto, (max-width: 761px) 100vw, 761px\" \/><\/a><\/p>\n<p>Next up, like any other function, we need an argument list: (). Where is the return value? Turns out that we don\u2019t need to give one. In C++11, if the compiler can deduce the return value of the lambda function, it will do it rather than force you to include it. In this case, the compiler knows the function returns nothing. Next we have the body, printing out \u201cHello World\u201d. This line of code doesn\u2019t actually cause anything to print out though\u2013we\u2019re just creating the function here. It\u2019s almost like defining a normal function\u2013it just happens to be inline with the rest of the code.<\/p>\n<p>It\u2019s only on the next line that we call the lambda function: func() \u2014 it looks just like calling any other function. By the way, notice how easy this is to do with <a href=\"http:\/\/www.cprogramming.com\/c++11\/c++11-auto-decltype-return-value-after-function.html\">auto<\/a>! You don\u2019t need to sweat the ugly syntax of a function pointer.<\/p>\n<h2>Variable Capture with Lambdas<\/h2>\n<p>Although these kinds of simple uses of lambd are nice, variable capture is the real secret sauce that makes a lambda function great. Let\u2019s imagine that you want to create a small function that finds addresses that contain a specific name. Wouldn\u2019t it be nice if you could write code something like this?<\/p>\n<pre class=\"example\">AdressBook global_adress_book;\r\n\/\/ read in the name from a user, which we want to search\r\nstring name;\r\ncin&gt;&gt; name;\r\nreturn global_address_book.findMatchingAddresses( \r\n    \/\/ notice that the lambda function uses the the variable 'name'\r\n    [&amp;] (const string&amp; addr) { return addr.find( name ) != string::npos; } \r\n);\r\n<\/pre>\n<p>It turns out that this example is completely legal\u2013and it shows the real value of lambda. We\u2019re able to take a variable declared outside of the lambda (name), and use it inside of the lambda. When findMatchingAddresses calls our lambda function, all the code inside of it executes\u2013and when addr.find is called, it has access to the name that the user passed in. The only thing we needed to do to make it work is tell the compiler we wanted to have variable capture. I did that by putting [&amp;] for the capture specification, rather than []. The empty [] tells the compiler not to capture any variables, whereas the [&amp;] specification tells the compiler to perform variable capture.<\/p>\n<h3>Return Values<\/h3>\n<p>By default, if your lambda does not have a return statement, it defaults to void. If you have a simple return expression, the compiler will deduce the type of the return value:<\/p>\n<pre class=\"example\">[] () { return 1; } \/\/ compiler knows this returns an integer<\/pre>\n<pre class=\"example\">[] () -&gt; int { return 1; } \/\/ now we're telling the compiler what we want<\/pre>\n<h2>How are Lambda Closures Implemented ?<\/h2>\n<ul>\n<li>[] Capture nothing (or, a scorched earth strategy?)<\/li>\n<li>[&amp;] Capture any referenced variable by reference<\/li>\n<li>[=] Capture any referenced variable by making a copy<\/li>\n<li>[=, &amp;foo] Capture any referenced variable by making a copy, but capture variable foo by reference<\/li>\n<li>[bar] Capture bar by making a copy; don\u2019t copy anything else<\/li>\n<li>[this] Capture the this pointer of the enclosing class<\/li>\n<\/ul>\n<h3>A Note About Function Pointers<\/h3>\n<pre class=\"example\">typedef int (*func)();\r\nfunc f = [] () -&gt; int { return 2; };\r\nf();<\/pre>\n<p><\/p>\n<\/body>","protected":false},"excerpt":{"rendered":"<p>The problem C++ includes useful generic functions like std::for_each and std::transform, which can be very handy. Unfortunately they can also<\/p>\n","protected":false},"author":1,"featured_media":271,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[7],"tags":[24,26,27],"class_list":["post-246","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-coding","tag-c","tag-code","tag-programming"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/imalogic.com\/blog\/wp-content\/uploads\/2017\/05\/lambda.png?fit=204%2C300&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8J21V-3Y","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts\/246","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/comments?post=246"}],"version-history":[{"count":2,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts\/246\/revisions"}],"predecessor-version":[{"id":276,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/posts\/246\/revisions\/276"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/media\/271"}],"wp:attachment":[{"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/media?parent=246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/categories?post=246"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/imalogic.com\/blog\/wp-json\/wp\/v2\/tags?post=246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}