{"id":5549,"date":"2018-11-01T04:34:03","date_gmt":"2018-11-01T04:34:03","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-for-template-interfaces\/"},"modified":"2023-06-26T11:42:13","modified_gmt":"2023-06-26T11:42:13","slug":"c-core-guidelines-rules-for-template-interfaces","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-for-template-interfaces\/","title":{"rendered":"C++ Core Guidelines: Pass Function Objects as Operations"},"content":{"rendered":"<p>An interface is a contract between a user and an implementer and should, therefore, be written with great care. This also holds true if you pass an operation as an argument.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5540\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/contract.png\" alt=\"contract\" width=\"500\" height=\"544\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/contract.png 1177w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/contract-276x300.png 276w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/contract-942x1024.png 942w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/contract-768x835.png 768w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>Today, I&#8217;m just writing about rule 40 because function objects are used quite heavily in modern C++.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<\/p>\n<p> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<\/p>\n<h2><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rt-fo\" style=\"color: #268bd2; text-decoration: none;\">T.40: Use function objects to pass operations to algorithms<\/a><\/h2>\n<p>First, you may be irritated that the rules didn&#8217;t explicitly mention lambda functions but use them. Later, I will write about this point in detail.<\/p>\n<p>There are various ways to sort a vector of strings.<\/p>\n<p>&nbsp;<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ functionObjects.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;algorithm&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;functional&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iterator&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;vector&gt;<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">bool<\/span> <span style=\"color: #cc00ff;\">lessLength<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> f, <span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> s){      <span style=\"color: #0099ff; font-style: italic;\">\/\/ (6) <\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> f.length() <span style=\"color: #555555;\">&lt;<\/span> s.length();\r\n}\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">GreaterLength<\/span>{                                              <span style=\"color: #0099ff; font-style: italic;\">\/\/ (7)<\/span>\r\n    <span style=\"color: #9999ff;\">public:<\/span>\r\n        <span style=\"color: #007788; font-weight: bold;\">bool<\/span> <span style=\"color: #006699; font-weight: bold;\">operator<\/span>()(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> f, <span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> s) <span style=\"color: #006699; font-weight: bold;\">const<\/span>{\r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> f.length() <span style=\"color: #555555;\">&gt;<\/span> s.length();\r\n    }\r\n};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>vector<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&gt;<\/span> myStrVec <span style=\"color: #555555;\">=<\/span> {<span style=\"color: #cc3300;\">\"523345\"<\/span>, <span style=\"color: #cc3300;\">\"4336893456\"<\/span>, <span style=\"color: #cc3300;\">\"7234\"<\/span>, \r\n\t                                     <span style=\"color: #cc3300;\">\"564\"<\/span>, <span style=\"color: #cc3300;\">\"199\"<\/span>, <span style=\"color: #cc3300;\">\"433\"<\/span>, <span style=\"color: #cc3300;\">\"2435345\"<\/span>};\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;                                      \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ascending with function object\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;  \r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), std<span style=\"color: #555555;\">::<\/span>less<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&gt;<\/span>()); <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span><span style=\"color: #555555;\">&amp;<\/span> str<span style=\"color: #555555;\">:<\/span> myStrVec) std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> str <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" \"<\/span>;  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"descending with function object\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;             \r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), std<span style=\"color: #555555;\">::<\/span>greater<span style=\"color: #555555;\">&lt;&gt;<\/span>());         <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span><span style=\"color: #555555;\">&amp;<\/span> str<span style=\"color: #555555;\">:<\/span> myStrVec) std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> str <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" \"<\/span>;  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ascending by length with function\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), lessLength);               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span><span style=\"color: #555555;\">&amp;<\/span> str<span style=\"color: #555555;\">:<\/span> myStrVec) std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> str <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" \"<\/span>;  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"descending by length with function object\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), GreaterLength());          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span><span style=\"color: #555555;\">&amp;<\/span> str<span style=\"color: #555555;\">:<\/span> myStrVec) std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> str <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" \"<\/span>;  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"ascending by length with lambda function\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(),                           <span style=\"color: #0099ff; font-style: italic;\">\/\/ (5)<\/span>\r\n              [](<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> f, <span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> s){ \r\n\t\t          <span style=\"color: #006699; font-weight: bold;\">return<\/span> f.length() <span style=\"color: #555555;\">&lt;<\/span> s.length(); \r\n\t\t\t  });\r\n    <span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #006699; font-weight: bold;\">auto<\/span><span style=\"color: #555555;\">&amp;<\/span> str<span style=\"color: #555555;\">:<\/span> myStrVec) std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> str <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" \"<\/span>;  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<article>\n<p>The program sorts a vector of strings lexicographically and based on the length of the strings. I&nbsp;used in lines (1) and (2) two function objects from the Standard template library. A function object is an instance of a class for which the call operator (<span style=\"font-family: courier new, courier;\">operater ()<\/span>) is overloaded. Often, there are falsely called functors. I hope, you notice the difference between the call<span style=\"font-family: courier new, courier;\"> std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), std<span style=\"color: #555555;\">::<\/span>less<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&gt;<\/span>())<\/span> in line (1) and <span style=\"font-family: courier new, courier;\">std<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), std<span style=\"color: #555555;\">::<\/span>greater<span style=\"color: #555555;\">&lt;&gt;<\/span>())<\/span>in&nbsp;line (2). The second expression (<span style=\"font-family: courier new, courier;\">std<span style=\"color: #555555;\">::<\/span>greater<span style=\"color: #555555;\">&lt;&gt;<\/span>()<\/span>), in which I provided no type for the predicate, has been valid since C++14. I sorted in lines (3), (4), and (5) by using a function (6), a function object (7), and a lambda function (5). This time, the length of the strings was the sorting criterion.<\/p>\n<\/article>\n<p>For completeness, here is the output of the program.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5541\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/functionObjects.png\" alt=\"functionObjects\" width=\"500\" height=\"357\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/functionObjects.png 815w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/functionObjects-300x214.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/functionObjects-768x548.png 768w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>The rules state you should <span style=\"color: #000000;\">&#8220;<a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rt-fo\" style=\"color: #000000;\">Use function objects to pass operations to algorithms&#8221;. <\/a><\/span><\/p>\n<h3>Advantages of function objects<\/h3>\n<p><span style=\"color: #000000;\"><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rt-fo\" style=\"color: #000000;\">My argumentation includes three points: Performance, Expressiveness, and State. It makes my answer that lambda functions are function objects under the hood relatively easy. <\/a><\/span><\/p>\n<h4>Performance<\/h4>\n<p>The more the optimizer can reason locally, the more optimization is possible. A function object (4) or a lambda function (5) can be generated just in place. Compare this to a function that was defined in a different translation unit. If you don&#8217;t believe me, use the <a href=\"https:\/\/godbolt.org\/\">compiler explorer<\/a> and compare the assembler instructions. Of course, compile with maximum optimization.<\/p>\n<h4>Expressiveness<\/h4>\n<p>&#8220;Explicit is better than implicit&#8221;. This meta-rule from Python also applies to C++. It means that your code should explicitly express its intent. Of course, this holds particularly for lambda functions such as line (5). Compare this with the function <span style=\"font-family: courier new, courier;\">lessLength<\/span> in line (6) used in line (3). Imagine your coworker would name the function <span style=\"font-family: courier new, courier;\">foo<\/span>; therefore, you have no idea what the function should do. You have to document its usage, such as in the following line.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ sorts the vector ascending, based on the length of its strings <\/span>\r\nstd<span style=\"color: #555555;\">::<\/span>sort(myStrVec.begin(), myStrVec.end(), foo); <span style=\"color: #0099ff; font-style: italic;\"><\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Further, you have to hope that your coworker wrote a correct predicate. If you don&#8217;t believe him, you must consider the implementation. Maybe that&#8217;s not possible because you have the declaration of the function. With a lambda function, your coworker can not fool you. The code is the truth. Let me put it more provocatively:&nbsp;<strong>Your code should be such expressive that it needs no documentation.&nbsp; <\/strong><\/p>\n<h4>State<\/h4>\n<p>In contrast to a function, a function object can have a state. The code example makes my point.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ sumUp.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;algorithm&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;vector&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">SumMe<\/span>{\r\n  <span style=\"color: #007788; font-weight: bold;\">int<\/span> sum{<span style=\"color: #ff6600;\">0<\/span>};\r\n  <span style=\"color: #9999ff;\">public:<\/span>\r\n    SumMe() <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">default<\/span>;\r\n\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">operator<\/span>()(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x){\r\n      sum <span style=\"color: #555555;\">+=<\/span> x;\r\n    }\r\n\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">getSum<\/span>(){\r\n      <span style=\"color: #006699; font-weight: bold;\">return<\/span> sum;\r\n    }\r\n};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>vector<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> intVec{<span style=\"color: #ff6600;\">1<\/span>, <span style=\"color: #ff6600;\">2<\/span>, <span style=\"color: #ff6600;\">3<\/span>, <span style=\"color: #ff6600;\">4<\/span>, <span style=\"color: #ff6600;\">5<\/span>, <span style=\"color: #ff6600;\">6<\/span>, <span style=\"color: #ff6600;\">7<\/span>, <span style=\"color: #ff6600;\">8<\/span>, <span style=\"color: #ff6600;\">9<\/span>, <span style=\"color: #ff6600;\">10<\/span>}; \r\n\r\n    SumMe sumMe<span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>for_each(intVec.begin(), intVec.end(), SumMe()); <span style=\"color: #0099ff; font-style: italic;\"> \/\/ (1)<\/span>\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Sum of intVec= \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> sumMe.getSum() <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;      <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The <span style=\"font-family: courier new, courier;\">std::for_each<\/span> call in line (1) is crucial.<span style=\"font-family: courier new, courier;\"> std::for_each<\/span>&nbsp;is a unique algorithm of the Standard Template Library because it can return its callable. I invoke <span style=\"font-family: courier new, courier;\">std::for_each<\/span> with the function object <span style=\"font-family: courier new, courier;\">SumMe<\/span> and can, therefore, store the result of the function call directly in the function object. I ask in line (2) for the sum of all calls, which is the state of the function object.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5542\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sumUp.png\" alt=\"sumUp\" width=\"350\" height=\"187\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sumUp.png 560w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sumUp-300x161.png 300w\" sizes=\"auto, (max-width: 350px) 100vw, 350px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>Just to be complete. Lambda functions can also have stated. You can use a lambda function to accumulate the values.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ sumUpLambda.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;algorithm&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;vector&gt;<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n\t\r\n\tstd<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>vector<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> intVec{<span style=\"color: #ff6600;\">1<\/span>, <span style=\"color: #ff6600;\">2<\/span>, <span style=\"color: #ff6600;\">3<\/span>, <span style=\"color: #ff6600;\">4<\/span>, <span style=\"color: #ff6600;\">5<\/span>, <span style=\"color: #ff6600;\">6<\/span>, <span style=\"color: #ff6600;\">7<\/span>, <span style=\"color: #ff6600;\">8<\/span>, <span style=\"color: #ff6600;\">9<\/span>, <span style=\"color: #ff6600;\">10<\/span>};\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>for_each(intVec.begin(), intVec.end(),\r\n\t            [sum <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">0<\/span>](<span style=\"color: #007788; font-weight: bold;\">int<\/span> i) <span style=\"color: #006699; font-weight: bold;\">mutable<\/span> {\r\n\t\t\t\t    sum <span style=\"color: #555555;\">+=<\/span> i; \r\n\t\t\t\t    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> sum <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n\t\t\t\t});\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"<\/span><span style=\"color: #cc3300; font-weight: bold;\">\\n<\/span><span style=\"color: #cc3300;\">\"<\/span>;\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Okay, this lambda function looks scary. First, the variable <span style=\"font-family: courier new, courier;\">sum<\/span> represents the state of the lambda function. With C++14, the so-called initialization capture of lambdas is supported. <span style=\"font-family: courier new, courier;\">sum = 0&nbsp;<\/span>declares and initializes a variable of type <span style=\"font-family: courier new, courier;\">int<\/span>, which is only valid in the scope of the lambda function. Lambda functions are per default <span style=\"font-family: courier new, courier;\">const<\/span>. By declaring it as <span style=\"font-family: courier new, courier;\">mutable<\/span>, I can add the numbers to <span style=\"font-family: courier new, courier;\">sum<\/span>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5543\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sumUpLambda.png\" alt=\"sumUpLambda\" width=\"300\" height=\"263\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sumUpLambda.png 634w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sumUpLambda-300x263.png 300w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>I stated that lambda functions are functions objects under the hood. <a href=\"https:\/\/cppinsights.io\/\">C++ Insight<\/a> makes the proof for my statement a piece of cake.<\/p>\n<h3>Lambda Functions are Function Objects<\/h3>\n<p>A lambda function is just <a href=\"https:\/\/en.wikipedia.org\/wiki\/Syntactic_sugar\">syntactic sugar<\/a> for a function object which is instantiated in place. C++ Insight shows which transformations the compiler applies to lambda functions.<\/p>\n<p>Let&#8217;s start simple. When I run the following small lambda function in C++ Insight<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5544\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sourceLambda.PNG\" alt=\"sourceLambda\" width=\"400\" height=\"124\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sourceLambda.PNG 681w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sourceLambda-300x93.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>the tool gives me the unsugared syntactic sugar:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5545\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambda.PNG\" alt=\"insightLambda\" width=\"600\" height=\"329\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambda.PNG 930w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambda-300x165.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambda-768x421.png 768w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>The compiler generates a function object <span style=\"font-family: courier new, courier;\">__lamda_2_16<\/span> (lines 4 &#8211; 11), instantiates it in line 13, and uses it in line 14. That&#8217;s all!<\/p>\n<p>The next example is a little bit more complicated. Now, the lambda function <span style=\"font-family: courier new, courier;\">addTo<\/span> adds the sum to the variable c captured by copy.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5547\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sourceLambdaCapture.PNG\" alt=\"sourceLambdaCapture\" width=\"400\" height=\"111\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sourceLambdaCapture.PNG 604w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/sourceLambdaCapture-300x83.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>In this case, the autogenerated function object&nbsp;gets a member c and a constructor. This is the code from C++ Insight.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5548\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambdaCapture.PNG\" alt=\"insightLambdaCapture\" width=\"600\" height=\"502\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambdaCapture.PNG 715w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/11\/insightLambdaCapture-300x251.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>This was just the first rule for template interfaces. My <a href=\"http:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-template-interfaces\">next post<\/a> continues their story.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>An interface is a contract between a user and an implementer and should, therefore, be written with great care. This also holds true if you pass an operation as an argument.<\/p>\n","protected":false},"author":21,"featured_media":5540,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[459],"class_list":["post-5549","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-lambdas"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5549","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5549"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5549\/revisions"}],"predecessor-version":[{"id":6807,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5549\/revisions\/6807"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5540"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5549"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5549"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5549"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}