    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Designing C++ Interfaces - Templates</title>
        <link>https://members.accu.org/index.php/journals/434</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #44 - Aug 2001 + Programming Topics + Design of applications and programs</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c160/">44</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c67/">Design</a>
                    (236)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c160-65-67/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c160+65+67/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Designing C++ Interfaces - Templates</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 August 2001 17:46:07 +01:00 or Sun, 26 August 2001 17:46:07 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>During the transition to the <span class="emphasis"><em>modern
C++</em></span> of the ISO standard, several additions were made to
the language. Two of these - exceptions and templates - have above
all others influenced the way C++ interfaces are designed.</p>
<p>Three observations about templates in modern C++:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>They are the principal C++ mechanism for expressing a static
(that is, compile time) separation of four concerns - types, data
structures, operations and control flow are separable and
independently interchangeable.</p>
</li>
<li>
<p>A further level of indirection is introduced between the
<span class="emphasis"><em>design</em></span> coded by the
programmer, and the code produced once the template is
instantiated.</p>
</li>
<li>
<p>The compiler now has the capability to write C++ code for the
programmer! That is, the compiler can accept input in the form a
powerful <span class="emphasis"><em>meta-language</em></span>
called a template, which tells the it how you want your generated
C++ code to look.</p>
</li>
</ul>
</div>
<p>The rest of this article presents an example of each of these
points in turn.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e45" id="d0e45"></a>Compile Time
Separation of Concerns</h2>
</div>
<p>The way this normally comes across is in the
commonality/variability separation, because a template is normally
viewed in terms of one aspect - in other words, one concern - being
varied while everything else remains constant. For example, the C++
Standard Library sequenced container class templates are
representative of the separation of two of the four concerns
mentioned above: types and structures. Consider the following
implicit specialisation of the list container class template
provided by the C++ standard library:</p>
<pre class="programlisting">
std::list&lt;int&gt; list_of_ints;
</pre>
<p>Here, the contained type, <span class="type">int</span>, is the
variable part, while the machinery for managing a list of
<span class="type">int</span> values - that is, the structure - is
common and could manage a list of <span class=
"emphasis"><em>any</em></span> type.</p>
<p>Although in the above example only two of the four concerns were
present, use of the C++ Standard Library algorithms is often
representative of all four concerns being present at the same
time.</p>
<p>Consider the process of searching for a particular object within
a container. The standard library provides an algorithm called
<tt class="function">find_if()</tt>, which provides an abstraction
of control flow. The container and contained type are included
indirectly via a pair of iterators. In addition, <tt class=
"function">find_if()</tt> takes a function object as a parameter:
this function object is an example of an operation (to be performed
within the flow of control).</p>
<p>This logic is applicable regardless of the type of element of
the sequence, and the implementation of the sequence could be any
type of sequenced container, or could even be a file from which the
elements are read. The operation of determining whether or not the
sought element has been found or not is delegated to a function
object.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e75" id="d0e75"></a>Compile Time
Indirection</h2>
</div>
<p>Suppose, within a namespace called whatever, we wish to write a
function called <tt class="function">some_function()</tt> which
makes use of a stack of integers. To simplify the implementation of
<tt class="function">some_function()</tt>, we wish to factor out
some of the processing, delegating it to a function called
<tt class="function">uses_stack()</tt>. Given that the <span class=
"emphasis"><em>purpose</em></span> of <tt class=
"function">uses_stack()</tt> is just to absorb factored out
processing, it makes sense to declare it locally in the anonymous
namespace within the implementation file.</p>
<p>This leaves <tt class="function">some_function()</tt> looking
like this:</p>
<pre class="programlisting">
namespace whatever
{
  void some_function()
  {
    typedef std::stack&lt;int&gt; stack_type;
    stack_type the_stack;
    uses_stack(the_stack);
// ... and the rest ...
  }
}
</pre>
<p>Here we face a problem: how to declare the function <tt class=
"function">uses_stack()</tt>, because the parameter type is not
know until within the block scope where it is actually being
called.</p>
<p>One solution is just to hoist</p>
<pre class="programlisting">
typedef std::stack&lt;int&gt; stack_type;
</pre>
<p>to the top of the implementation file, and place it also in the
anonymous namespace. This has the advantage of being simple, but at
the same time, it removes from <tt class=
"function">some_function()</tt> something which is an
implementation detail of that function.</p>
<p>There is another solution: by using templates, and introducing
another level of indirection at compile time, the declaration of
<tt class="function">uses_stack()</tt> can be deferred until the
point at which it is called!</p>
<p>The code now looks like this:</p>
<pre class="programlisting">
namespace
{
  template &lt;typename type&gt;
    void uses_stack(std::stack&lt;type&gt;&amp; s);
}
namespace whatever
{
  void some_function()
  {
    std::stack&lt;int&gt; the_stack;
    uses_stack(the_stack);
    // ... and the rest ...
  }
}
</pre>
<p>The definition of <tt class="function">uses_stack()</tt> is
omitted for brevity (where it is placed is a matter of preference,
as in this case it is declared, defined and used all within a
single implementation file).</p>
<p>The type of <tt class="classname">the_stack</tt> - and note that
the introduction of a template has rendered the use of the
<tt class="literal">typedef</tt> unnecessary - can now be placed
where we'd like it. Naturally though, nothing comes for free, and
we now have a different set of tradeoffs to consider. The plus
points have already been mentioned in the discussion leading up to
here; however there is a minus point in that the function
<tt class="function">uses_stack()</tt> is generalised - and made
generic - even though in usage terms, no generalisation is
required. This is over generalisation, because no generalisation
was necessary, regardless of the usefulness of the function
template as a means of indirection. Therefore the code has become
more complex in one respect, whereas it has become simpler in
another (the <tt class="literal">typedef</tt> is now encapsulated
within <tt class="function">uses_stack()</tt>).</p>
<p>This is quite a simple example of the use of a template to
introduce a level of compile time indirection: a far more striking
example can be found in an article by Alan Griffiths [<a href=
"#ARG">ARG</a>].</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e152" id="d0e152"></a>Code
Generation</h2>
</div>
<p>The place where the power of templates becomes most apparent is
in the use of the C++ compiler as a C++ <span class=
"emphasis"><em>code generator</em></span>! Indeed, in their recent
book [<a href="#C_E">C_E</a>] authors Czarnecki and Eisenecker
devote lots of space to this code generation approach.</p>
<p>By way of example consider the software to control a video
recorder. Different models have different features, and here let's
consider the inclusion or not of the ability to respond to the PDC
signal.</p>
<p>The VCR which can handle the PDC (Programme Delivery Centre)
signal will be more expensive: what are you actually paying for
when you pay more money? Two things spring to mind (not exhaustive
of course): more onboard memory, and extra software. Therefore our
design goals include excluding the PDC handling functionality from
the onboard s/w of the cheaper model. With all this in mind, the
software will be designed in terms of a common structure, and
within this, variability will be implemented by <span class=
"emphasis"><em>policy classes</em></span> [<a href="#AA">AA</a>],
which will be parameters in the interfaces of the classes which
they help implement.</p>
<p>The PDC handling code is therefore factored into the following
policy class templates (actually structs - the use of structs is
typical for policies):</p>
<pre class="programlisting">
template &lt;bool has_pdc&gt; struct pdc_feature
{
  static void handle_pdc()
  {
       :
    /* code */
       :
  }
};
// and specialisation:
template &lt;&gt; struct pdc_feature&lt;false&gt;
{
  static void handle_pdc()
  { /* Empty! */  }
};
</pre>
<p>Another feature common to more expensive models is extra fast
forward and rewind. Imagine we factor the code to handle this in a
similar way, and we also have the following enum:</p>
<pre class="programlisting">
enum vcr_model_type
{
  basic_model,
  middle_of_the_road_model,
  deluxe_model
};
</pre>
<p>And the configuration templates:</p>
<pre class="programlisting">
// No general case, 
// each needs a specialisation
template &lt;vcr_model_type vcr_model&gt;
  struct vcr_feature_configuration;
template &lt;&gt; struct vcr_feature_configuration&lt;
      middle_of_the_road_model &gt;
{
  static bool const has_pdc = false;
  static bool const has_fast_winding = true;
};
template &lt;&gt; struct vcr_feature_configuration&lt; deluxe_model &gt;
{
  static bool const has_pdc = true;
  static bool const has_fast_winding = true;
};
</pre>
<p>Then we can base the onboard VCR s/w around operations expressed
in the template:</p>
<pre class="programlisting">
template &lt;vcr_model_type vcr_model&gt;
  struct vcr_onboard_software
{
  typedef typename
    vcr_feature_configuration&lt;vcr_model&gt;
              configuration;
  static bool const has_pdc =
              configuration::has_pdc;
  static void handle_pdc()
  {
    pdc_feature&lt;has_pdc&gt;::handle_pdc();
  }
  // ... And the same sort of
  // thing for fast winding ...
};
</pre>
<p>So we can now generate the software in its configuration for the
deluxe model by instantiating the template</p>
<pre class="programlisting">
vcr_onboard_software&lt;deluxe_model&gt;
    delux_model_vcr_sw;
</pre>
<p>and similarly for the other models.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e195" id="d0e195"></a>Summary</h2>
</div>
<p>Consider again, the second example illustrating compile time
indirection. In this example, as a consequence of making <tt class=
"function">uses_stack()</tt> into a function template, the
separation of structure and type concerns spilled over into
<tt class="function">users_stack()</tt>'s interface. Further, the
extra level of indirection was available because a declaration of
<tt class="function">uses_stack()</tt> with a stack of integers as
its parameter type:</p>
<pre class="programlisting">
void uses_stack(std::stack&lt;int&gt;&amp; s);
</pre>
<p>was <span class="emphasis"><em>generated</em></span> after the
point where the parameter type became known!</p>
<p>This article's introduction presented three observations about
the presence of templates in C++. Each of these observations
presents one aspect of templates, none of which are independent of
the others - they are all present to some degree in any C++ code
that uses templates.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e218" id="d0e218"></a>References</h2>
</div>
<div class="bibliomixed"><a name="AA" id="AA"></a>
<p class="bibliomixed">[AA] Andrei Alexandrescu: <span class=
"citetitle"><i class="citetitle">Modern C++ Design: Generic
Programming and Design Patterns Applied</i></span>, Addison-Wesley
2001.</p>
</div>
<div class="bibliomixed"><a name="ARG" id="ARG"></a>
<p class="bibliomixed">[ARG] Alan Griffiths: Compile Time
Indirection - An Unusual Template Technique, <span class=
"citetitle"><i class="citetitle">Overload 42</i></span>.</p>
</div>
<div class="bibliomixed"><a name="C_E" id="C_E"></a>
<p class="bibliomixed">[C_E] Krzysztof Czarnecki and Ulrich W.
Eisenecker: <span class="citetitle"><i class="citetitle">Generative
Programming: Methods, Tools and Applications</i></span>,
Addison-Wesley 2000.</p>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] Erich Gamma, Richard Helm, Ralph
Johnson and John Vlissides: <span class="citetitle"><i class=
"citetitle">Design Patterns: Elements of Reusable Object-Oriented
Software</i></span>, Addison-Wesley, 1995.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
