{"id":5134,"date":"2017-01-19T06:58:34","date_gmt":"2017-01-19T06:58:34","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/functional-in-c-dispatch-table\/"},"modified":"2023-06-26T12:26:41","modified_gmt":"2023-06-26T12:26:41","slug":"functional-in-c-dispatch-table","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/functional-in-c-dispatch-table\/","title":{"rendered":"Functional in C++11 and C++14: Dispatch Table and Generic Lambdas"},"content":{"rendered":"<p>My favorite example, the dispatch table, shows how nicely the features in modern C++ work together. A <a href=\"https:\/\/en.wikipedia.org\/wiki\/Dispatch_table\">dispatch table <\/a>is a table of pointers to functions. In my case, it is a table of handles for polymorphic function wrappers.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p>But at first, what do I mean by modern C++? I use the dispatch table features from C++11. I added this post, C++14, to the timeline. Why? You will see it later.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5130\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/timeline.FunktionalInCpp11Cpp14Eng.png\" alt=\"timeline.FunktionalInCpp11Cpp14Eng\" width=\"700\" height=\"351\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/timeline.FunktionalInCpp11Cpp14Eng.png 948w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/timeline.FunktionalInCpp11Cpp14Eng-300x151.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/timeline.FunktionalInCpp11Cpp14Eng-768x386.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<h2>Dispatch table<\/h2>\n<p><em>Thanks to <a href=\"http:\/\/arne-mertz.de\/\">Arne Mertz<\/a>, I used the C++11 features uniform initialization in combination with an initializer list. That further improved the following example.<\/em><\/p>\n<p>The example shows a simple dispatch table that maps characters to function objects.<em><\/em><\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29\r\n30\r\n31<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ dispatchTable.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;cmath&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;functional&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;map&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n\r\n  std::cout &lt;&lt; std::endl;\r\n\r\n  <span style=\"color: #008000;\">\/\/ dispatch table<\/span>\r\n  std::map&lt; <span style=\"color: #0000ff;\">const<\/span> <span style=\"color: #2b91af;\">char<\/span> , std::function&lt;<span style=\"color: #2b91af;\">double<\/span>(<span style=\"color: #2b91af;\">double<\/span>,<span style=\"color: #2b91af;\">double<\/span>)&gt; &gt; dispTable{\r\n    {<span style=\"color: #a31515;\">'+'<\/span>,[](<span style=\"color: #2b91af;\">double<\/span> a, <span style=\"color: #2b91af;\">double<\/span> b){ <span style=\"color: #0000ff;\">return<\/span> a + b;} },\r\n    {<span style=\"color: #a31515;\">'-'<\/span>,[](<span style=\"color: #2b91af;\">double<\/span> a, <span style=\"color: #2b91af;\">double<\/span> b){ <span style=\"color: #0000ff;\">return<\/span> a - b;} },\r\n    {<span style=\"color: #a31515;\">'*'<\/span>,[](<span style=\"color: #2b91af;\">double<\/span> a, <span style=\"color: #2b91af;\">double<\/span> b){ <span style=\"color: #0000ff;\">return<\/span> a * b;} },\r\n    {<span style=\"color: #a31515;\">'\/'<\/span>,[](<span style=\"color: #2b91af;\">double<\/span> a, <span style=\"color: #2b91af;\">double<\/span> b){ <span style=\"color: #0000ff;\">return<\/span> a \/ b;} } };\r\n\r\n  <span style=\"color: #008000;\">\/\/ do the math<\/span>\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"3.5+4.5= \"<\/span> &lt;&lt; dispTable[<span style=\"color: #a31515;\">'+'<\/span>](3.5,4.5) &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"3.5-4.5= \"<\/span> &lt;&lt; dispTable[<span style=\"color: #a31515;\">'-'<\/span>](3.5,4.5) &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"3.5*4.5= \"<\/span> &lt;&lt; dispTable[<span style=\"color: #a31515;\">'*'<\/span>](3.5,4.5) &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"3.5\/4.5= \"<\/span> &lt;&lt; dispTable[<span style=\"color: #a31515;\">'\/'<\/span>](3.5,4.5) &lt;&lt; std::endl;\r\n\r\n  <span style=\"color: #008000;\">\/\/ add a new operation<\/span>\r\n  dispTable[<span style=\"color: #a31515;\">'^'<\/span>]=  [](<span style=\"color: #2b91af;\">double<\/span> a, <span style=\"color: #2b91af;\">double<\/span> b){ <span style=\"color: #0000ff;\">return<\/span> std::pow(a,b);};\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"3.5^4.5= \"<\/span> &lt;&lt; dispTable[<span style=\"color: #a31515;\">'^'<\/span>](3.5,4.5) &lt;&lt; std::endl;\r\n\r\n  std::cout &lt;&lt; std::endl;\r\n\r\n};\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>How does the magic work? The dispatch table is, in my case, a <span style=\"font-family: courier new,courier;\">std::map<\/span> that contains pairs of <span style=\"font-family: courier new,courier;\">const char<\/span> and<span style=\"font-family: courier new,courier;\">&nbsp;std::function&lt;double(double, double)<\/span>. Of course, you can use a <span style=\"font-family: courier new,courier;\">std::unordered_map<\/span> instead of a <span style=\"font-family: courier new,courier;\">std::map. std::function<\/span> is a so-called polymorphic function wrapper. Thanks to <span style=\"font-family: courier new,courier;\">std::function<\/span>, it can take all that behaves like a function. This can be a function, a function object, or a lambda function (lines 14 -17). The only requirements of <span style=\"font-family: courier new,courier;\">std::function&lt;double(double, double)&gt;<\/span> are that its entities need two <span style=\"font-family: courier new,courier;\">double<\/span> arguments and return a <span style=\"font-family: courier new,courier;\">double<\/span> argument. The lambda functions fulfill this requirement.<\/p>\n<p>I use the function object in lines 20 &#8211; 23. Therefore, the call of <span style=\"font-family: courier new,courier;\">dispTable[&#8216;+&#8217;] <\/span>in line 20 returns that function object, which was initialized by the lambda function <span style=\"font-family: courier new,courier;\">[](double a, double b){ return a + b; }<\/span> (line 14). To execute the function object, two arguments are needed. I use them in the expression<span style=\"font-family: courier new,courier;\"> dispTable[&#8216;+&#8217;](3.5, 4.5).<\/span><\/p>\n<p>A <span style=\"font-family: courier new,courier;\">std::map<\/span> is a dynamic data structure. Therefore, I can add and use the <span style=\"font-family: courier new,courier;\">&#8216;^&#8217;<\/span> operation (line 27) at runtime. Here is the calculation.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5131\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/dispatchTable.png\" alt=\"dispatchTable\" style=\"margin: 15px;\" width=\"427\" height=\"240\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/dispatchTable.png 427w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/dispatchTable-300x169.png 300w\" sizes=\"auto, (max-width: 427px) 100vw, 427px\" \/><\/p>\n<p>Still, a short explanation is missing. Why is this my favorite example in C++?<\/p>\n<\/p>\n<h3>Like in Python<\/h3>\n<p>I often give Python seminars. A dispatch table is one of my favorite examples to motivate the easy usage of Python. That is, by the way, the reason why Python needs no case statement.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\"># dispatchTable.py<\/span>\r\n\r\ndispTable={\r\n  <span style=\"color: #a31515;\">\"+\"<\/span>: (<span style=\"color: #0000ff;\">lambda<\/span> x, y: x+y),\r\n  <span style=\"color: #a31515;\">\"-\"<\/span>: (<span style=\"color: #0000ff;\">lambda<\/span> x, y: x-y),  \r\n  <span style=\"color: #a31515;\">\"*\"<\/span>: (<span style=\"color: #0000ff;\">lambda<\/span> x, y: x*y),\r\n  <span style=\"color: #a31515;\">\"\/\"<\/span>: (<span style=\"color: #0000ff;\">lambda<\/span> x, y: x\/y)\r\n}\r\n\r\n<span style=\"color: #0000ff;\">print<\/span>\r\n\r\n<span style=\"color: #0000ff;\">print<\/span> <span style=\"color: #a31515;\">\"3.5+4.5= \"<\/span>, dispTable[<span style=\"color: #a31515;\">'+'<\/span>](3.5, 4.5)\r\n<span style=\"color: #0000ff;\">print<\/span> <span style=\"color: #a31515;\">\"3.5-4.5= \"<\/span>, dispTable[<span style=\"color: #a31515;\">'-'<\/span>](3.5, 4.5)\r\n<span style=\"color: #0000ff;\">print<\/span> <span style=\"color: #a31515;\">\"3.5*4.5= \"<\/span>, dispTable[<span style=\"color: #a31515;\">'*'<\/span>](3.5, 4.5)\r\n<span style=\"color: #0000ff;\">print<\/span> <span style=\"color: #a31515;\">\"3.5\/4.5= \"<\/span>, dispTable[<span style=\"color: #a31515;\">'\/'<\/span>](3.5, 4.5)\r\n\r\ndispTable[<span style=\"color: #a31515;\">'^'<\/span>]= <span style=\"color: #0000ff;\">lambda<\/span> x, y: pow(x,y)\r\n<span style=\"color: #0000ff;\">print<\/span> <span style=\"color: #a31515;\">\"3.5^4.5= \"<\/span>, dispTable[<span style=\"color: #a31515;\">'^'<\/span>](3.5, 4.5)\r\n\r\n<span style=\"color: #0000ff;\">print<\/span>\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The implementation is based on the functional features of Python. Thanks to <span style=\"font-family: courier new,courier;\">std::map,<\/span> <span style=\"font-family: courier new,courier;\">std::function,<\/span> and lambda-functions, I can now use the same example in C++11 to emphasize the expressive power of C++. A fact I would not have dreamed of ten years ago.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5132\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/dispatchTablePython.png\" alt=\"dispatchTablePython\" style=\"margin: 15px;\" width=\"375\" height=\"245\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/dispatchTablePython.png 375w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/dispatchTablePython-300x196.png 300w\" sizes=\"auto, (max-width: 375px) 100vw, 375px\" \/>&nbsp;<\/p>\n<h2>Generic lambda-functions<\/h2>\n<p>I almost forgot it. Lambda functions become more potent with C++14. Lambda function can automatically deduce the types of its arguments. The feature is based on automatic type deduction with <span style=\"font-family: courier new,courier;\">auto.<\/span> Of course, lambda functions and automatic type deduction are characteristics of functional programming.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ generalizedLambda.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;string&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;typeinfo&gt;<\/span>\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n    \r\n  std::cout &lt;&lt; std::endl;\r\n  \r\n  <span style=\"color: #0000ff;\">auto<\/span> myAdd= [](<span style=\"color: #0000ff;\">auto<\/span> fir, <span style=\"color: #0000ff;\">auto<\/span> sec){ <span style=\"color: #0000ff;\">return<\/span> fir+sec; };\r\n  \r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myAdd(1, 10)= \"<\/span> &lt;&lt; myAdd(1, 10) &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myAdd(1, 10.0)= \"<\/span> &lt;&lt; myAdd(1, 10.0) &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myAdd(std::string(1),std::string(10.0)= \"<\/span> \r\n            &lt;&lt;  myAdd(std::string(<span style=\"color: #a31515;\">\"1\"<\/span>),std::string(<span style=\"color: #a31515;\">\"10\"<\/span>)) &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"myAdd(true, 10.0)= \"<\/span> &lt;&lt; myAdd(true, 10.0) &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"typeid(myAdd(1, 10)).name()= \"<\/span> &lt;&lt; <span style=\"color: #0000ff;\">typeid<\/span>(myAdd(1, 10)).name() &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"typeid(myAdd(1, 10.0)).name()= \"<\/span> &lt;&lt; <span style=\"color: #0000ff;\">typeid<\/span>(myAdd(1, 10.0)).name() &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"typeid(myAdd(std::string(1), std::string(10))).name()= \"<\/span> \r\n            &lt;&lt; <span style=\"color: #0000ff;\">typeid<\/span>(myAdd(std::string(<span style=\"color: #a31515;\">\"1\"<\/span>), std::string(<span style=\"color: #a31515;\">\"10\"<\/span>))).name() &lt;&lt; std::endl;\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"typeid(myAdd(true, 10.0)).name()= \"<\/span> &lt;&lt; <span style=\"color: #0000ff;\">typeid<\/span>(myAdd(true, 10.0)).name() &lt;&lt; std::endl;\r\n    \r\n  std::cout &lt;&lt; std::endl;\r\n\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>In line 11, I use the generic lambda function. This function can be invoked with arbitrary types for its arguments <span style=\"font-family: courier new,courier;\">fir<\/span> and <span style=\"font-family: courier new,courier;\">second<\/span> and deduces in addition automatically its return type. To use the lambda function, I gave the lambda function the name <span style=\"font-family: courier new,courier;\">myAdd.<\/span> Line 13 &#8211; 17 shows the application of the lambda function. Of course, I&#8217;m interested in which type the compiler derives for the return type. For that, I use the <span style=\"font-family: courier new,courier;\">typeid<\/span> operator in lines 21 -25. This operator needs the header <span style=\"font-family: courier new,courier;\">&lt;typeinfo&gt;.<\/span><\/p>\n<p>The <span style=\"font-family: courier new,courier;\">typeid<\/span> operator is not so reliable. It returns a C string, which depends on the implementation. You have not guaranteed that the C string is different for different types nor that the C string is the same for each program invocation. But for our use case, the <span style=\"font-family: courier new,courier;\">typeid<\/span> operator is reliable enough.<\/p>\n<p>My desktop PC is broken. Therefore I execute the program at <a href=\"http:\/\/en.cppreference.com\/w\/\">cppreference.com.<\/a><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5133\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/generalizedLambdaFunctions.png\" alt=\"generalizedLambdaFunctions\" width=\"700\" height=\"236\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/generalizedLambdaFunctions.png 903w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/generalizedLambdaFunctions-300x101.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/01\/generalizedLambdaFunctions-768x259.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>The output shows the different return types. The C string<span style=\"font-family: courier new,courier;\"> i<\/span> and <span style=\"font-family: courier new,courier;\">d<\/span> stands for the types <span style=\"font-family: courier new,courier;\">int<\/span> and <span style=\"font-family: courier new,courier;\">double.<\/span> The type of the C++ strings is not so good readable. But you can see that <span style=\"font-family: courier new,courier;\">std::string<\/span> is an alias for<span style=\"font-family: courier new,courier;\"> std::basic_string. <\/span><\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>In the <a href=\"https:\/\/www.modernescpp.com\/index.php\/functional-in-c-17-and-c-20\">next post<\/a>, I will write about the near and distant functional future of C++. With C++17 and C++20, the functional aspect of C++ becomes more powerful.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>My favorite example, the dispatch table, shows how nicely the features in modern C++ work together. A dispatch table is a table of pointers to functions. In my case, it is a table of handles for polymorphic function wrappers.<\/p>\n","protected":false},"author":21,"featured_media":5130,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[365],"tags":[472,459,412],"class_list":["post-5134","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-functional","tag-associative-containers","tag-lambdas","tag-python"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5134","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=5134"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5134\/revisions"}],"predecessor-version":[{"id":6897,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5134\/revisions\/6897"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5130"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5134"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5134"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5134"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}