{"id":6306,"date":"2022-02-18T12:27:07","date_gmt":"2022-02-18T12:27:07","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/dynamic-and-static-polymorphism\/"},"modified":"2023-08-12T16:19:45","modified_gmt":"2023-08-12T16:19:45","slug":"dynamic-and-static-polymorphism","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/dynamic-and-static-polymorphism\/","title":{"rendered":"Dynamic and Static Polymorphism"},"content":{"rendered":"<p>Polymorphism is the property that different types support the same interface. In C++, we distinguish between dynamic polymorphism and static polymorphism.<\/p>\n<p><!--more--><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6303\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/StaticDynamic.png\" alt=\"StaticDynamic\" width=\"650\" height=\"394\" 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>Now we are done with the basics, details, and techniques around templates, let me write about the design with templates. There are many types of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Polymorphism_(computer_science)\">polymorphism<\/a>, but I want to concentrate on one aspect. Does the polymorphism dispatch happen at run time or at compile time? Run-time polymorphism is based on object orientation and virtual functions in C++, and compile-time polymorphism is based on templates.<\/p>\n<p>Both polymorphisms have pros and cons that I discuss in the following post.<\/p>\n<h2>Dynamic Polymorphism<\/h2>\n<p>Here are the key facts. Dynamic Polymorphism takes place at run time, is based on object orientation, and enables us to separate between the interface and the implementation of a class hierarchy. To get late binding, dynamic dispatch, or dispatch at run time, you need virtuality and an indirection such as a pointer or a reference.<\/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>\n\n#include &lt;chrono&gt;<\/span>\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\n\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();\n\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeElapsedTime<\/span>(){\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();\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;\n  \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>;\n}\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageSeverity{                         \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> {         \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>;\n\t}\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageInformation<span style=\"color: #555555;\">:<\/span> MessageSeverity{     \n\t<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {        \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>;\n\t}\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageWarning<span style=\"color: #555555;\">:<\/span> MessageSeverity{         \n\t<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> override {        \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>;\n\t}\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageFatal<span style=\"color: #555555;\">:<\/span> MessageSeverity{};\n\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>\n\t\n\twriteElapsedTime();\n\tmessServer.writeMessage();\n\t\n}\n\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>\n\t\n\twriteElapsedTime();\n\tmessServer<span style=\"color: #555555;\">-&gt;<\/span>writeMessage();\n\t\n}\n\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  \n    MessageInformation messInfo;\n    MessageWarning messWarn;\n    MessageFatal messFatal;\n  \n    MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messRef1 <span style=\"color: #555555;\">=<\/span> messInfo;       <em><span style=\"color: #0099ff;\"> \/\/ (3)<\/span> <\/em>     \n    MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messRef2 <span style=\"color: #555555;\">=<\/span> messWarn;      <em><span style=\"color: #0099ff;\">  \/\/ (4)<\/span><\/em>\n    MessageSeverity<span style=\"color: #555555;\">&amp;<\/span> messRef3 <span style=\"color: #555555;\">=<\/span> messFatal;      <em><span style=\"color: #0099ff;\"> \/\/ (5)<\/span><\/em>\n  \n    writeMessageReference(messRef1);              \n    writeMessageReference(messRef2);\n    writeMessageReference(messRef3);\n  \n    std<span style=\"color: #555555;\">::<\/span>cerr <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  \n    MessageSeverity<span style=\"color: #555555;\">*<\/span> messPoin1 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> MessageInformation;   <em><span style=\"color: #0099ff;\">\/\/ (6)<\/span><\/em>\n    MessageSeverity<span style=\"color: #555555;\">*<\/span> messPoin2 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> MessageWarning;      <em> <span style=\"color: #0099ff;\">\/\/ (7)<\/span><\/em>\n    MessageSeverity<span style=\"color: #555555;\">*<\/span> messPoin3 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> MessageFatal;        <em> <span style=\"color: #0099ff;\">\/\/ (8)<\/span><\/em>\n  \n    writeMessagePointer(messPoin1);               \n    writeMessagePointer(messPoin2);\n    writeMessagePointer(messPoin3);\n  \n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n}\n<\/pre>\n<\/div>\n<p>The function <code>writeMessageReference<\/code> (line 1) or <code>writeMessagePointer<\/code> (line 2) require a reference or a pointer to an object of type<code> MessageSeverity<\/code>. Classes publicly derived from <code>MessageSeverity<\/code> such as <code>MessageInformation<\/code>, <code>MessageWarning<\/code>, or <code>MessageFatal<\/code> support the so-called\u00a0<a href=\"https:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle\">Liskov substitution principle<\/a>. This means that a <code>MessageInformation<\/code>, <code>MessageWarning<\/code>, or a <code>MessageFatal<\/code> is a <code>MessageSeverity<\/code>.<\/p>\n<p>Here is the output of the program.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6304\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/dispatchDyamicPolymorphis.png\" alt=\"dispatchDyamicPolymorphis\" width=\"450\" height=\"303\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/dispatchDyamicPolymorphis.png 500w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/dispatchDyamicPolymorphis-300x202.png 300w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><\/p>\n<p>You may ask yourself why the member function <code>writeMessage<\/code> of the derived class and not the base class is called. Here, late binding kicks in. The following explanation applies to lines (3) to (8). For simplicity, I only write about the line (6): <code>MessageSeverity* messPoin1 = new MessageInformation<\/code>. messPoint1 has essentially two types. A static type <code>MessageSeverity<\/code> and a dynamic type <code>MessageInformation<\/code>. The static type <code>MessageSeverity<\/code> stands for its interface, and the dynamic type<code> MessageInformation<\/code> for its implementation. The static type is used at compile time, and the dynamic type at run time. At run time, messPoint1 is of type <code>MessageInformation<\/code>; therefore, the virtual function <code>writeMessage<\/code> of <code>MessageInformation<\/code> is called. Once more, dynamic dispatch requires an indirection such as a pointer or reference and virtuality.<\/p>\n<p>I regard this kind of polymorphism as a<strong> contract-driven design.<\/strong> A function such as <code>writeMessagePointer<\/code> requires that each object has to support that it is publicly derived from <code>MessageSeverity<\/code>. If this contract is not fulfilled, the compiler complains.<\/p>\n<p>In contrast to contract-driven design, we also have a<strong> behavioral-driven design<\/strong> with static polymorphism.<\/p>\n<h2>Static Polymorphism<\/h2>\n<p>Let me start with a short detour.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" alignleft size-full wp-image-5499\" style=\"margin: 20px; float: left;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/09\/snake-312561_1280.png\" alt=\"snake 312561 1280\" width=\"200\" height=\"178\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/09\/snake-312561_1280.png 1280w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/09\/snake-312561_1280-300x268.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/09\/snake-312561_1280-1024x915.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/09\/snake-312561_1280-768x686.png 768w\" sizes=\"auto, (max-width: 200px) 100vw, 200px\" \/><\/p>\n<p>In Python, you care about behavior and not about formal interfaces. This idea is well-known as <a href=\"https:\/\/en.wikipedia.org\/wiki\/Duck_typing\">duck typing. <\/a>To make it short, the expression goes back to the poem from <a href=\"https:\/\/de.wikipedia.org\/wiki\/James_Whitcomb_Riley\">James <\/a><a href=\"https:\/\/de.wikipedia.org\/wiki\/James_Whitcomb_Riley\">Whitcomb<\/a><a href=\"https:\/\/de.wikipedia.org\/wiki\/James_Whitcomb_Riley\"> Rileys:<\/a> Here it is:<\/p>\n<p>\u201cWhen I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.\u201d<\/p>\n<p>What does that mean? Imagine a function <code>acceptOnlyDucks<\/code>\u00a0that only accepts ducks as an argument. In statically typed languages such as C++, all types which are derived from\u00a0 <code>Duck<\/code> can be used to invoke the function. In Python, all types, which behave like <code>Duck<\/code>&#8216;s, can be used to invoke the function. To make it more concrete. If a bird behaves like a <code>Duck,<\/code> it is a <code>Duck<\/code>. Python often uses a proverb to describe this behavior quite well.<\/p>\n<p>Don&#8217;t ask for permission; ask for forgiveness.<\/p>\n<p>In our Duck&#8217;s case, you invoke the function <code>acceptsOnlyDucks<\/code> with a bird and hope for the best. If something terrible happens, you catch the exception with an except clause. Typically, this strategy works very well and very fast in Python.<\/p>\n<p>Okay, this is the end of my detour. Maybe you wonder why I wrote about duck typing in this C++ post. The reason is relatively straightforward. Thanks to templates, we have duck typing in C++.<\/p>\n<p>This means that you can refactor the previous program <code>dispatchStaticPolymorphism.cpp<\/code> using duck typing.<\/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: 0; line-height: 125%;\"><span style=\"color: #009999;\"><span style=\"color: #3366ff;\">\/\/ duckTyping.cpp<\/span>\n\n#include &lt;chrono&gt;<\/span>\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\n\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();\n\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeElapsedTime<\/span>(){\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();\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;\n  \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>;\n}\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageSeverity{\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\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> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageInformation {\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {              \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> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageWarning {\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {               \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> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageFatal<span style=\"color: #555555;\">:<\/span> MessageSeverity{};     \n\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>\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage(T<span style=\"color: #555555;\">&amp;<\/span> messServer){    <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)                   <\/span>\n\t\n\twriteElapsedTime();                                   \n\tmessServer.writeMessage();                            \n\t\n}\n\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> main(){\n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  \n    MessageInformation messInfo;\n    writeMessage(messInfo);\n    \n    MessageWarning messWarn;\n    writeMessage(messWarn);\n\n    MessageFatal messFatal;\n    writeMessage(messFatal);\n  \n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n}\n<\/pre>\n<\/div>\n<p>The function template <code>writeMessage<\/code> (line 1) applies duck typing. <code>writeMessage<\/code> assumes that all objects messServer support the member function <code>writeMessage<\/code>. If not, the compilation would fail. The main difference to Python is that the error happens in C++ at compile time, but in Python at run time. Finally, here is the output of the program.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6305\" style=\"display: block; margin-left: auto; margin-right: auto;\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/duckTyping.png\" alt=\"duckTyping\" width=\"400\" height=\"228\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/duckTyping.png 425w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/02\/duckTyping-300x171.png 300w\" sizes=\"auto, (max-width: 400px) 100vw, 400px\" \/><\/p>\n<p>The function <code>writeMessage<\/code> behaves polymorphic but is neither type-safe nor writes a readable error message in case of an error. At least I can quickly fix the last issue with concepts in C++20. You can read more about concepts in my previous posts about <a href=\"https:\/\/www.modernescpp.com\/index.php\/tag\/concepts\">concepts<\/a>. In the following example, I define and use the concept<code> MessageServer<\/code> (line 1).<\/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: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ duckTypingWithConcept.cpp<\/span>\n\n<span style=\"color: #009999;\">#include &lt;chrono&gt;<\/span>\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\n\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>\nconcept MessageServer <span style=\"color: #555555;\">=<\/span> requires(T t) {\n    t.writeMessage();\n};\n\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();\n\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">writeElapsedTime<\/span>(){\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();\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;\n  \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>;\n}\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageSeverity{\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\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> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageInformation {\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {              \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> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageWarning {\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage() <span style=\"color: #006699; font-weight: bold;\">const<\/span> {               \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> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  }\n};\n\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> MessageFatal<span style=\"color: #555555;\">:<\/span> MessageSeverity{};     \n\n<span style=\"color: #006699; font-weight: bold;\">template<\/span> <span style=\"color: #555555;\">&lt;<\/span>MessageServer T<span style=\"color: #555555;\">&gt;<\/span>   <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> writeMessage(T<span style=\"color: #555555;\">&amp;<\/span> messServer){                       \n\t\n\twriteElapsedTime();                                   \n\tmessServer.writeMessage();                            \n\t\n}\n\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> main(){\n\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n  \n    MessageInformation messInfo;\n    writeMessage(messInfo);\n    \n    MessageWarning messWarn;\n    writeMessage(messWarn);\n\n    MessageFatal messFatal;\n    writeMessage(messFatal);\n  \n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\n\n}\n<\/pre>\n<\/div>\n<p>The concept MessageServer (line 1) requires that an object <code>t<\/code> of type <code>T<\/code> has to support the call<code> t.writeMessage. <\/code>Line (2) applies the concept in the function template <code>writeMessage<\/code>.<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>So far, I have only written about the polymorphic behavior of templates but not static polymorphism. This changes in my next post. I present the so-called CRTP idiom. CRTP stands for the <strong>C<\/strong>uriously<strong> R<\/strong>ecurring <strong>T<\/strong>emplate <strong>P<\/strong>attern and means a technique in C++ in which you inherit a class <code>Derived<\/code> from a template class <code>Base<\/code> and <code>Base<\/code> has <code>Derived<\/code> as a template parameter:<\/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: 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>\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">Base<\/span>\n{\n    ...\n};\n\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>\n{\n    ...\n};\n<\/pre>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Polymorphism is the property that different types support the same interface. In C++, we distinguish between dynamic polymorphism and static polymorphism.<\/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-6306","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\/6306","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=6306"}],"version-history":[{"count":2,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6306\/revisions"}],"predecessor-version":[{"id":8055,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6306\/revisions\/8055"}],"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=6306"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6306"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6306"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}