{"id":928,"date":"2019-09-19T00:20:28","date_gmt":"2019-09-19T07:20:28","guid":{"rendered":"http:\/\/localhost\/imagecraft\/blog\/?p=928"},"modified":"2019-09-19T00:20:28","modified_gmt":"2019-09-19T07:20:28","slug":"stepping-up-to-c-templates","status":"publish","type":"post","link":"https:\/\/imagecraft.com\/?p=928","title":{"rendered":"Stepping Up to C++ Templates"},"content":{"rendered":"\n<p>In the first decade after C++ was released, there were two frequent statements made about the new programming language, especially in the C community:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>C allows you to shoot your foot off, but C++ allows you to shoot the whole leg off.<\/li><li>C++ is &#8220;just an object-oriented language&#8221;.<\/li><\/ol>\n\n\n\n<p>If you have heard of either of these, it\u2019s time to put those ideas away. Looking at C++ in 2019, it\u2019s clearly a rich language that provides many features for writing safe, efficient code, using concepts such as generic programming. The expressive power of modern C++ comes mainly from the use of templates and their uses in generic programming, and not so much from object-oriented concepts (although it does support object-oriented programming with class inheritance and virtual functions). This article introduces some of the basic ideas with templates.<\/p>\n\n\n\n<p>Over their years of programming, most C programmers will have accumulated sets of routines for linked lists, arrays, stacks etc. in their coding libraries; for example, stack routines for pushing, popping, and searching for items on a stack. In C++, you may implement a stack for holding integer data with code that looks something like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class int_stack {\n public :\n     bool push(int item);\n     int pop(void);\n \u2026\n };<\/pre>\n\n\n\n<p>A class is basically a struct declaration that includes member functions and other advanced features. The declaration above declares a class name \u201cint_stack\u201d, which contains two member functions, push and pop, and other items not listed here (shown as &#8220;\u2026&#8221;).<\/p>\n\n\n\n<p>In C, a set of such routines would only work for one data type (e.g., int). If you want stack routines for double data types, you will have to duplicate the routines, and change the names and internals to work with double data types, though most of the code would be identical. If you are clever, perhaps you might use void pointers and such to make the same set of routines work with different data types, but it would be a hack.<\/p>\n\n\n\n<p>C++ templates solve that. Here\u2019s an example of a template stack class:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">template &lt;typename T&gt; stack {\npublic:\n bool push (T item);\n T pop(void);\n\u2026\n};<\/pre>\n\n\n\n<p><strong>Note 1<\/strong>: This is just a simple example. The actual implementation of the stack in the standard C++ library STL (Standard Template Library) is far more capable and complex than this example.<\/p>\n\n\n\n<p><strong>Note 2<\/strong>: You may also write the template declaration with the word \u201cclass\u201d instead of \u201ctypename\u201d, e.g. \u201ctemplate &lt;class T&gt; stack { \u2026\u201d.<\/p>\n\n\n\n<p>A template declaration such as above does not create anything per se, not even a class type. However, if you use it to declare variables, e.g.:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">stack&lt;int&gt; int_stack;\nstack&lt;double&gt; double_stack; <\/pre>\n\n\n\n<p>\u201cstack&lt;int&gt;\u201d is known as a <em>parameterized type<\/em>. With these two declarations, the compiler creates two declarations, as if you have written something akin to:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class int_stack {\npublic :\n bool push(int item);\n int pop(void);\n\u2026\n};\n\nclass d_stack {\npublic :\n bool push(double item);\n double pop(void);\n\u2026\n};<\/pre>\n\n\n\n<p>Templates eliminate having to write similar-looking code, reducing the effort to write and maintain a project. Note that there is only one template name (\u201cstack\u201d) which is decorated with the actual data type to declare a class type (e.g. \u201cstack&lt;int&gt;\u201d). While this simple example might be done using clever C preprocessing macros, the full power of templates cannot be replaced by C macros.<\/p>\n\n\n\n<p>If you use the template declaration multiple times, e.g:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">stack&lt;int&gt; stack1; \nstack&lt;int&gt; stack2; <\/pre>\n\n\n\n<p>The compiler is smart enough to know that the two implicitly created stack classes are the same.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Baby Steps to Generic Programming<\/h2>\n\n\n\n<p>Now imagine you want to add an \u201c==\u201d equality operator to the stack class (in C++, you can <em>overload<\/em> the meaning of any C operator symbol within a class, but you cannot create new operator symbols that do not exist in the base language):<\/p>\n\n\n\n<p>To do this, first, let\u2019s look at an example of <em>non-template <\/em>operator definition:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class int_stack {\n public :\n    bool push(int item);\n    int pop(void);\n    bool operator==(int_stack &amp;);\n \u2026\n };\n <\/pre>\n\n\n\n<p>The definition of the operator, if written outside of the class declaration, starts with:  <\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> bool int_stack::operator==(int_stack &amp;stack2) ... <\/pre>\n\n\n\n<p>This declaration is for an == operator of a non-template class \u201cint_stack\u201d. In this example, there are two symbols not used in C:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>:: is the scope resolution operator. The left-hand side is either a class name or a namespace name (we will not be discussing namespace in this short article). In this example, you can think of the words \u201cint_stack::operator==\u201d to mean \u201cthis is the == operator for the int_stack class\u201d.<\/li><li>&amp;, as used in a variable declaration, after the type name and before the variable name as shown above, signifies that this is a <em>reference<\/em> to the variable. A reference has the same semantic as a pointer-to a variable (i.e. in a function call, a reference parameter allows efficient passing of the argument, and allows the function to modify the argument), except that you don\u2019t use the * indirect operator to access the variable, as the variable name itself suffices. For a struct\/class variable, this means that you use the dot \u201c.\u201d field member operator, instead of the \u201c-&gt;\u201d field member operator.<\/li><\/ol>\n\n\n\n<p>For a template, operator declaration is just a little bit more complicated:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">template &lt;typename T&gt; stack {\n public:\n     bool push (T item);\n     T pop(void);\n     bool operator==(stack&lt;T&gt; &amp;stack2);\n \u2026\n };<\/pre>\n\n\n\n<p>The definition of the operator, if written outside of the class declaration, starts with: <\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">template &lt;typename T&gt; bool stack&lt;T&gt;::operator==(stack&lt;T&gt; &amp;stack2) \u2026 <\/pre>\n\n\n\n<p>A parameterized type \u201cstack&lt;T&gt;\u201d is used in place of a concrete type \u201cint_stack\u201d and the whole declaration is prefixed with \u201ctemplate &lt;typename T&gt;\u201d to tell the compiler that this is a template declaration. Once you understand the basics of operator declaration, this is just a bit more syntactic sugar on top.<\/p>\n\n\n\n<p>The code for the template == operator could be something as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">template &lt;typename T&gt; bool stack&lt;T&gt;::operator==(stack&lt;T&gt; &amp;stack2)\n     {\n     if (size() != stack2.size())\n         return false;\n     <code>for (unsigned i = 0; i &lt; size(); i++)     <\/code>\n         <code>if (elems[i] != stack2[i])         <\/code>\n             <code>return false; <\/code>\n    <code>return true; <\/code>\n    <code>}<\/code><\/pre>\n\n\n\n<p>There is a lot to unpack here. Looking at the code, you may make the following observations:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The stack class supports a size() function, presumably to indicate the number of elements in the class.<\/li><li>The stack class includes a member named \u201celems\u201d, presumably containing the actual elements of the stack.<\/li><li>The stack class supports an array indexing [i] operator, where [i] presumably returns the i\u2019th sequential member of the stack.<\/li><li>You may apply the array indexing [] to either a class object (e.g. stack2[i]) or to the elements member (e.g. elems[i]), presumably with the same semantic effect.<\/li><li>Each element is compared against the element in the other stack in the same position. This implies that the element data type must support the == and != operators as well.<\/li><\/ol>\n\n\n\n<p>Taking together, the function returns true if and only if the stacks have the same number of elements and each element compares equality.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Power of Templates<\/h2>\n\n\n\n<p>So why is this important? The template mechanism allows the above code to work for any stack&lt;T&gt; objects, as long as they implement the features as noted above. Not only does this reduce the amount of code you have to write, it allows you to use templates (and their routines) written by other people, saving you much design, implementation, and debugging time.<\/p>\n\n\n\n<p>I have already mentioned the STL (Standard Template Library), which provides templates for stacks, vectors, lists, hash tables, etc. There are more advanced libraries such as Boost, which provides support for linear algebra, pseudorandom number generation, multithreading, image processing, regular expressions, and unit testing. Boost contains over eighty individual libraries. Without templates, STL and Boost would not have been possible.<\/p>\n\n\n\n<p>Any C++ programmers who haven&#8217;t done so yet should get familiar with STL and Boost libraries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">More C++: Iterators and New FOR loop<\/h2>\n\n\n\n<p>Instead of using array indexing syntax, most classes that support sequential access also provides <em>iterators<\/em>, and the above function can be rewritten (only the main loop is given here) as:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for (auto &amp; iter = elems.begin(); iter != elems.end(); iter++)\n    {\n    if (iter != stack2[i])\n        return false;\n    ++i;\n    }<\/pre>\n\n\n\n<p>So what are the differences?<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The C keyword \u201cauto\u201d has now been repurposed to request the compiler to deduce the data type of the variable automatically. The compiler does this by looking at the type of the right hand side of the assignment expression. There is no need to write out the data type for \u201citer\u201d. This is a powerful feature, especially if the data type declaration is complex (the data type for an iterator is indeed fairly complex).<\/li><li>There are iterator functions and idioms that allow you to sequentially access the elements of the stack just like using the array indexing [i].<\/li><\/ol>\n\n\n\n<p>As they say, <em>there\u2019s more!<\/em> Instead of using explicit iterator, you can also write:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for (auto &amp; elem::elems)\n    {\n    if (elem != stack2[i])\n        return false;\n    } <\/pre>\n\n\n\n<p>This new \u201cfor\u201d loop syntax, which assumes an iterator over a class object, combined with \u201cauto\u201d type deduction, allow you to iterate through the elements simply and elegantly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A Stupid Implementation<\/h2>\n\n\n\n<p>If you just want to get your feet wet and become familiar with C++ syntax, you can implement a dumb version of the stack template based on the STL\u2019s vector class. Of course the STL has a far more capable version of stack template with a lot more features, but nothing beats learning a language by actually typing in some code:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#include &lt;vector>\n\ntemplate &lt;typename T>\nclass stack {\npublic:\n\u00a0\u00a0\u00a0\u00a0bool push(T item) { elems.push_back(item); return true; }\n\u00a0\u00a0\u00a0\u00a0T pop(void) { T val = elems.back(); elems.pop_back(); return val; }\n\u00a0\u00a0\u00a0\u00a0bool operator==(stack&lt;T> &amp;stack2);\n\u00a0\u00a0\u00a0\u00a0unsigned size(void) { return elems.size(); }\n\u00a0\u00a0\u00a0\u00a0T&amp; operator[](int i);\n\nprivate:\n\u00a0\u00a0\u00a0\u00a0vector&lt;T> elems;\n};<\/pre>\n\n\n\n<p>The \u201c==\u201d operator is as described above, and I will leave it as an exercise to the readers to implement the [] array indexing operator. <\/p>\n\n\n\n<p>You can write a simple test like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">int main() \n    {\n&nbsp;&nbsp;&nbsp;&nbsp;stack&lt;int&gt; istack, istack2;\n\n&nbsp;&nbsp;&nbsp;&nbsp;istack.push(42);\n&nbsp;&nbsp;&nbsp;&nbsp;istack.push(1000);\n&nbsp;&nbsp;&nbsp;&nbsp;int x = istack.pop();\n\n&nbsp;&nbsp;&nbsp;&nbsp;cout &lt;&lt; \"Hello world! x is \" &lt;&lt; x &lt;&lt; endl;\n\n&nbsp;&nbsp;&nbsp;&nbsp;if (istack == istack2)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout &lt;&lt; \"stacks equal\" &lt;&lt; endl;\n\n&nbsp;&nbsp;&nbsp;&nbsp;cout &lt;&lt; istack.pop() &lt;&lt; endl;\n&nbsp;&nbsp;&nbsp;&nbsp;if (istack == istack2)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout &lt;&lt; \"stacks equal\" &lt;&lt; endl;\n&nbsp;&nbsp;&nbsp; } <\/pre>\n\n\n\n<p>When run, you should see:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Hello world! x is 1000\n42\nstacks equal<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p>C++ is a mature programming language, capable to efficiently write high performance programs. The core of its usability and efficiency is the extensive use of templates. This article only briefly scratches what is possible.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the first decade after C++ was released, there were two frequent statements made about the new programming language, especially in the C community: C allows you to shoot your foot off, but C++ allows you to shoot the whole leg off. C++ is &#8220;just an object-oriented language&#8221;. If you have heard of either of these, it\u2019s time to put those ideas away. Looking at C++ in 2019, it\u2019s clearly a rich language that provides many features for writing safe, efficient code, using concepts such as generic programming. The expressive power of modern C++ comes mainly from the use of [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-gradient":""}},"footnotes":""},"categories":[1],"tags":[],"class_list":["post-928","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/imagecraft.com\/index.php?rest_route=\/wp\/v2\/posts\/928","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/imagecraft.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/imagecraft.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/imagecraft.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/imagecraft.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=928"}],"version-history":[{"count":0,"href":"https:\/\/imagecraft.com\/index.php?rest_route=\/wp\/v2\/posts\/928\/revisions"}],"wp:attachment":[{"href":"https:\/\/imagecraft.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=928"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/imagecraft.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=928"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/imagecraft.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=928"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}