{"id":6309,"date":"2022-02-25T07:17:10","date_gmt":"2022-02-25T07:17:10","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/more-about-dynamic-and-static-polymorhism\/"},"modified":"2023-06-26T09:12:32","modified_gmt":"2023-06-26T09:12:32","slug":"more-about-dynamic-and-static-polymorhism","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/more-about-dynamic-and-static-polymorhism\/","title":{"rendered":"More about Dynamic and Static Polymorphism"},"content":{"rendered":"<p>In my last post, &#8220;<a href=\"https:\/\/www.modernescpp.com\/index.php\/dynamic-and-static-polymorphism\">Dynamic and Static Polymorphism<\/a>&#8220;, I introduced dynamic polymorphism. Today, I continue with static polymorphism and present a very interesting idiom in C++: curiously recurring template pattern (CRTP).<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6303\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/StaticDynamic.png\" alt=\"\" width=\"650\" height=\"394\" style=\"display: block; margin-left: auto; margin-right: auto;\" data-alt=\"StaticDynamic\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/StaticDynamic.png 919w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/StaticDynamic-300x182.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/StaticDynamic-768x465.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>A short recap. This is where I left in my last post.<\/p>\n<p>Dynamic Polymorphism is based on object orientation and enables us to separate between the interface and the implementation of a class hierarchy. To get late dynamic dispatch, you need two ingredients: virtuality and an indirection such as a pointer or a reference. The following program exemplified dynamic polymorphism:<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #009999;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ dispatchDynamicPolymorphism.cpp<\/span><br \/><br \/>#include &lt;chrono&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">auto<\/span> start <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>chrono<span style=\"color: #555555;\">::<\/span>steady_clock<span style=\"color: #555555;\">::<\/span>now();\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeElapsedTime<\/span>(){\r\n    <span style=\"color: #006699; font-weight: bold;\">auto<\/span> now <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>chrono<span style=\"color: #555555;\">::<\/span>steady_clock<span style=\"color: #555555;\">::<\/span>now();\r\n    std<span style=\"color: #555555;\">::<\/span>chrono<span style=\"color: #555555;\">::<\/span>duration<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">double<\/span><span style=\"color: #555555;\">&gt;<\/span> diff <span style=\"color: #555555;\">=<\/span> now <span style=\"color: #555555;\">-<\/span> start;\r\n  \r\n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> diff.count() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" sec. elapsed: \"<\/span>;\r\n}\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageSeverity{                         \r\n\t<span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {         \r\n\t\tstd<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"unexpected\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\t}\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageInformation<span style=\"color: #555555;\">:<\/span> MessageSeverity{     \r\n\t<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {        \r\n\t\tstd<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"information\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\t}\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageWarning<span style=\"color: #555555;\">:<\/span> MessageSeverity{         \r\n\t<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {        \r\n\t\tstd<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"warning\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\t}\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageFatal<span style=\"color: #555555;\">:<\/span> MessageSeverity{};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeMessageReference<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messServer){  <span style=\"color: #0099ff;\"><em> \/\/ (1)<\/em><\/span>\r\n\t\r\n\twriteElapsedTime();\r\n\tmessServer.writeMessage();\r\n\t\r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeMessagePointer<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> MessageSeverity<span style=\"color: #555555;\">*<\/span> messServer){    <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n\t\r\n\twriteElapsedTime();\r\n\tmessServer<span style=\"color: #555555;\">-&gt;<\/span>writeMessage();\r\n\t\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>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n    MessageInformation messInfo;\r\n    MessageWarning messWarn;\r\n    MessageFatal messFatal;\r\n  \r\n    MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messRef1 <span style=\"color: #555555;\">=<\/span> messInfo;       <em><span style=\"color: #0099ff;\"> <\/span><\/em>     \r\n    MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messRef2 <span style=\"color: #555555;\">=<\/span> messWarn;      <em><span style=\"color: #0099ff;\">  <\/span><\/em>\r\n    MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messRef3 <span style=\"color: #555555;\">=<\/span> messFatal;      \r\n  \r\n    writeMessageReference(messRef1);              \r\n    writeMessageReference(messRef2);\r\n    writeMessageReference(messRef3);\r\n  \r\n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n    MessageSeverity<span style=\"color: #555555;\">*<\/span> messPoin1 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> MessageInformation;   \r\n    MessageSeverity<span style=\"color: #555555;\">*<\/span> messPoin2 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> MessageWarning;      <em> <\/em>\r\n    MessageSeverity<span style=\"color: #555555;\">*<\/span> messPoin3 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> MessageFatal;        <em> <\/em>\r\n  \r\n    writeMessagePointer(messPoin1);               \r\n    writeMessagePointer(messPoin2);\r\n    writeMessagePointer(messPoin3);\r\n  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Static polymorphism is based on templates. Refactor the program using the<strong> C<\/strong>uriously <strong>R<\/strong>ecurring<strong> T<\/strong>emplate<strong> P<\/strong>attern (CRTP).<\/p>\n<\/p>\n<h2>Static Polymorphism<\/h2>\n<p>Before I refactor the previous program<code> dispatchDynamicPolymorphism.cpp, <\/code>here is the key idea of CRTP: A class <code>Derived<\/code> derives from a class template <code>Base<\/code> and <code>Base<\/code> has <code>Derived<\/code> as a template argument.<\/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: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Base<\/span>\r\n{\r\n    ...\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Derived<\/span> <span style=\"color: #555555;\">:<\/span> <span style=\"color: #006699; font-weight: bold;\">public<\/span> Base<span style=\"color: #555555;\">&lt;<\/span>Derived<span style=\"color: #555555;\">&gt;<\/span>\r\n{\r\n    ...\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Here is the pure nature of CRTP:<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0px; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ crtp.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> Derived<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Base{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> interface(){                <em><span style=\"color: #0099ff;\">              \/\/ (2)<\/span><\/em>\r\n    <span style=\"color: #006699; font-weight: bold;\">static_cast<\/span><span style=\"color: #555555;\">&lt;<\/span>Derived<span style=\"color: #555555;\">*&gt;<\/span>(<span style=\"color: #006699; font-weight: bold;\">this<\/span>)<span style=\"color: #555555;\">-&gt;<\/span>implementation();\r\n  }\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> implementation(){                       <em><span style=\"color: #0099ff;\"> \/\/ (3)<\/span><\/em>\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Implementation Base\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived1<span style=\"color: #555555;\">:<\/span> Base<span style=\"color: #555555;\">&lt;<\/span>Derived1<span style=\"color: #555555;\">&gt;<\/span>{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> implementation(){\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Implementation Derived1\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived2<span style=\"color: #555555;\">:<\/span> Base<span style=\"color: #555555;\">&lt;<\/span>Derived2<span style=\"color: #555555;\">&gt;<\/span>{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> implementation(){\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"Implementation Derived2\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Derived3<span style=\"color: #555555;\">:<\/span> Base<span style=\"color: #555555;\">&lt;<\/span>Derived3<span style=\"color: #555555;\">&gt;<\/span>{};             <em><span style=\"color: #0099ff;\">\/\/ (4)<\/span><\/em>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>                          <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> execute(T<span style=\"color: #555555;\">&amp;<\/span> base){\r\n    base.interface();\r\n}\r\n\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> main(){\r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> '\\n';\r\n  \r\n  Derived1 d1;\r\n  execute(d1);\r\n    \r\n  Derived2 d2;\r\n  execute(d2);\r\n  \r\n  Derived3 d3;\r\n  execute(d3);\r\n  \r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> '\\n';\r\n  \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I use in the function template <code>execute<\/code> (line 1) static polymorphism. Each&nbsp;<span style=\"font-family: courier new,courier;\">base<\/span> invoked the method<code> base.interface<\/code><span style=\"font-family: courier new,courier;\">.<\/span> The member function <code>Base::interface<\/code> (line 2) is the key point of the CRTP idiom. The member function dispatches to the implementation of the derived class<em><\/em>: <span style=\"font-family: courier new,courier;\">static_cast&lt;Derived*&gt;(this)-&gt;implementation()<\/span>.&nbsp; That is possible because the method will be instantiated when called. At this point in time the derived classes <code>Derived1, Derived2<\/code>, and Derived3 are fully defined. Therefore, the method <span style=\"font-family: courier new,courier;\"><span style=\"font-family: courier new,courier;\">Base::interface<\/span> <\/span>can use the implementation of its derived classes. Pretty interesting is the member function <span style=\"font-family: courier new,courier;\">Base::implementation<\/span> (line 3). This function plays the role of a default implementation for the static polymorphism for the class&nbsp; <code>Derived3 <\/code>(line 4).<\/p>\n<p>Here is the output of the program:<\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6308\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/crtpNew.png\" alt=\"crtp\" width=\"250\" height=\"207\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/crtpNew.png 312w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/crtpNew-300x248.png 300w\" sizes=\"auto, (max-width: 250px) 100vw, 250px\" \/><\/p>\n<p>Now, let me take the next step and refactor the program <code>dispatchDynamicPolymorphism.cpp.<\/code><\/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;\">\/\/ dispatchStaticPolymorphism.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;chrono&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">auto<\/span> start <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>chrono<span style=\"color: #555555;\">::<\/span>steady_clock<span style=\"color: #555555;\">::<\/span>now();\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeElapsedTime<\/span>(){\r\n    <span style=\"color: #006699; font-weight: bold;\">auto<\/span> now <span style=\"color: #555555;\">=<\/span> std<span style=\"color: #555555;\">::<\/span>chrono<span style=\"color: #555555;\">::<\/span>steady_clock<span style=\"color: #555555;\">::<\/span>now();\r\n    std<span style=\"color: #555555;\">::<\/span>chrono<span style=\"color: #555555;\">::<\/span>duration<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">double<\/span><span style=\"color: #555555;\">&gt;<\/span> diff <span style=\"color: #555555;\">=<\/span> now <span style=\"color: #555555;\">-<\/span> start;\r\n  \r\n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> diff.count() <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" sec. elapsed: \"<\/span>;\r\n}\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> ConcreteMessage<span style=\"color: #555555;\">&gt;<\/span>                        <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageSeverity{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage(){                                     <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">static_cast<\/span><span style=\"color: #555555;\">&lt;<\/span>ConcreteMessage<span style=\"color: #555555;\">*&gt;<\/span>(<span style=\"color: #006699; font-weight: bold;\">this<\/span>)<span style=\"color: #555555;\">-&gt;<\/span>writeMessageImplementation();\r\n  }\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessageImplementation() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\r\n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"unexpected\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageInformation<span style=\"color: #555555;\">:<\/span> MessageSeverity<span style=\"color: #555555;\">&lt;<\/span>MessageInformation<span style=\"color: #555555;\">&gt;<\/span>{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessageImplementation() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"information\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageWarning<span style=\"color: #555555;\">:<\/span> MessageSeverity<span style=\"color: #555555;\">&lt;<\/span>MessageWarning<span style=\"color: #555555;\">&gt;<\/span>{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessageImplementation() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"warning\"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  }\r\n};\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageFatal<span style=\"color: #555555;\">:<\/span> MessageSeverity<span style=\"color: #555555;\">&lt;<\/span>MessageFatal<span style=\"color: #555555;\">&gt;<\/span>{};     <span style=\"color: #0099ff; font-style: italic;\">\/\/ (5)<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #006699; font-weight: bold;\">typename<\/span> T<span style=\"color: #555555;\">&gt;<\/span>\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage(T<span style=\"color: #555555;\">&amp;<\/span> messServer){                       \r\n\t\r\n    writeElapsedTime();                                   \r\n    messServer.writeMessage();                            <span style=\"color: #0099ff; font-style: italic;\">\/\/ (6)<\/span>\r\n\t\r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> main(){\r\n\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n  \r\n    MessageInformation messInfo;\r\n    writeMessage(messInfo);\r\n    \r\n    MessageWarning messWarn;\r\n    writeMessage(messWarn);\r\n\t\r\n    MessageFatal messFatal;\r\n    writeMessage(messFatal);\r\n  \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>In this case, all concrete classes (lines 3, 4, and 5) derive from the base class <code>MessageSeverity<\/code>. The member function <code>writeMessage <\/code>is the interface that dispatches to the concrete implementations <code>writeMessageImplementation<\/code>. To achieve this, the object will be upcasted to the <code>ConcreteMessage:&nbsp;&nbsp;static_cast&lt;ConcreteMessage*&gt;(this)-&gt;writeMessageImplementation();<\/code><span style=\"font-family: 'courier new', courier;\">. <\/span>This is the static dispatch at compile time and coined the name for this technique: static polymorphism.<\/p>\n<p>It took me time to get used to it, but applying the static polymorphism in line (6) is quite easy.<\/p>\n<p>In the end, I want to compare dynamic and static polymorphism in a few words:<\/p>\n<h2>Dynamic Versus Static Polymorphism<a href=\"https:\/\/www.modernescpp.com\/Dynamic%20and%20Static%20Polymorphism\"><\/a><\/h2>\n<p>Dynamic polymorphism happens at run time, and static polymorphism at compile time. Dynamic polymorphism typically requires a pointer indirection at run time (read the post &#8220;<a href=\"https:\/\/medium.com\/@abhichavhan\/demystifying-virtual-functions-vtable-and-vptr-in-c-bf56f11f7cc7\">Demystifying virtual functions, Vtable, and VPTR in C++<\/a>&#8220;), but static polymorphism has no performance costs at run time. Admittedly, there is a reason why the idiom curiously recurring template pattern (CRTP) has the name curious inside. For beginners, the idiom is quite challenging to understand. So, what should you use?<\/p>\n<p>First of all, don&#8217;t overestimate the costs of a virtual dispatch. In most cases, you can ignore them. Read the excellent paper &#8220;<a href=\"https:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/TR18015.pdf\">Technical Report on C++ Performance<\/a>&#8221; for details. It&#8217;s pretty dated but has in section 5.3.3 exciting numbers about the additional costs of virtual function calls. If you are still concerned about performance, there is only one cure: measure. Put your performance tests under version control. Always rerun them if something in your setup consisting of your hardware, compiler, or compiler version changes because this invalidates your previous performance numbers.<\/p>\n<p>In the end, code is way more often read the written. Therefore, you should use the techniques your team is most comfortable with. &nbsp;<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Mixin\">Mixins<\/a> are a widespread technique in Python. They allow you to change the behavior of a class using multiple inheritances. Thanks to CRTP, we also have mixins in C++. Read about them in my next post.<\/p>\n<p>&nbsp;<\/p>\n<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In my last post, &#8220;Dynamic and Static Polymorphism&#8220;, I introduced dynamic polymorphism. Today, I continue with static polymorphism and present a very interesting idiom in C++: curiously recurring template pattern (CRTP).<\/p>\n","protected":false},"author":21,"featured_media":6303,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[376],"tags":[427],"class_list":["post-6309","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-templates","tag-polymorphism"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6309","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=6309"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6309\/revisions"}],"predecessor-version":[{"id":6680,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6309\/revisions\/6680"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6303"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6309"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6309"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6309"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}