    <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  :: Template Metaprogramming: Shifting Down a Gear</title>
        <link>https://members.accu.org/index.php/articles/390</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>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #50 - Aug 2002</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/articles/">All</a>

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

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c195/">50</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-195/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+195/">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;Template Metaprogramming: Shifting Down a Gear</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 August 2002 22:58:29 +01:00 or Fri, 02 August 2002 22:58:29 +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>Template metaprogramming (MP) in C++ is a powerful technique but
the syntax used can be obscure and difficult to understand. Here I
propose an alternative approach in which a subset of the standard
C++ language is used to write template metaprograms in a natural
and familiar style.</p>
<p>This article assumes either an understanding of template
metaprogramming or a pretty good ability to absorb new ideas. If
you want to read up on the topic before reading this article: see
[<a href="#Veldhuizen1995">Veldhuizen1995</a>] online for Todd
Veldhuizen's historical paper and some useful links; and [<a href=
"#Walker2001">Walker2001</a>] for a recent <i class=
"citetitle">Overload</i> article on the subject.</p>
<p>There are a number of forms of MP but in this document we use
only the general-purpose one presented in Andrei Alexandrescu's
<i class="citetitle">Modern C++ Design</i> [<a href=
"#Alexandrescu2001">Alexandrescu2001</a>]; I will refer to this
form of MP as <i class="firstterm">AMP</i>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e44" id="d0e44"></a>Template
Metaprogramming</h2>
</div>
<p>C++ template-metaprogramming uses standard features of the
language to achieve computation in the type-domain, at compilation
time.</p>
<p>This means that computation is done on <span class=
"emphasis"><em>types</em></span> rather than on <span class=
"emphasis"><em>values</em></span>. This may sound bizarre but in
practice it can aid both in design abstraction and in time/space
efficiency. Applications of MP include high-performance numerical
computing [<a href="#Blitz">Blitz</a>], matrix computation
[<a href="#GMCL">GMCL</a>], reflection [<a href=
"#Attardi-">Attardi-</a>], dimensional analysis [<a href=
"#Barton-">Barton-</a>] and static configuration [<a href=
"#Breymann-">Breymann-</a>].</p>
<p>However, despite the power of the technique it isn't really used
in the mainstream, and it's been 8 years since Erwin Unruh wrote
the first MP program [<a href="#Unruh1994">Unruh1994</a>].</p>
<p>This may be due in part to a lack of suitable C++ compilers in
the past but another reason must be that MP is not a <span class=
"emphasis"><em>designed</em></span> part of the language: it's
really an accident resulting from the interaction of several
language features. And - as so often happens when something is used
for other than its intended purpose - MP code can be obscure and
difficult to understand.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e82" id="d0e82"></a>factorial
Example</h2>
</div>
<p>Let's start by implementing the factorial function as a template
metaprogram.</p>
<p>Here is a standard implementation of the factorial function:</p>
<pre class="programlisting">
int factorial(int n) {
  if (n==1) {
    return 1;
  }
  else {
    return n*factorial(n-1);
  }
}
...
// example call
int x = factorial(5);
</pre>
<p>The two branches of the conditional statement return the two
possible outcomes:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>when <tt class="literal">n==1</tt> the function simply returns
1</p>
</li>
<li>
<p>when <tt class="literal">n!=1</tt> the function returns the
result of calling itself recursively with an argument of <tt class=
"literal">n-1</tt></p>
</li>
</ul>
</div>
<p>Here is an MP implementation of the factorial
function<sup>[<a name="d0e110" href="#ftn.d0e110" id=
"d0e110">1</a>]</sup>:</p>
<pre class="programlisting">
// definition
template&lt;int n&gt;
struct factorial {
  enum {RET = n*factorial&lt;n-1&gt;::RET};
};
// partial specialization
template&lt;&gt;
struct factorial&lt;1&gt; {
  enum {RET = 1};
};
...
// example call
enum {x = factorial&lt;5&gt;::RET};
</pre>
<p>The definition and partial specialization of the factorial class
template here give the two possible outcomes:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>when <tt class="literal">n!=1</tt> the result is given by the
result of instantiating itself recursively with a template argument
of <tt class="literal">n-1</tt></p>
</li>
<li>
<p>when <tt class="literal">n==1</tt> the result is simply 1</p>
</li>
</ul>
</div>
<p>Compare the possible outcomes of the function with those of the
class. Although the factorial class looks very different from the
factorial function they have the same logical structure :-</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>return 1 if the parameter is 1</p>
</li>
<li>
<p>return <tt class="varname">n</tt> times the factorial of
<tt class="literal">n-1</tt> otherwise</p>
</li>
</ul>
</div>
<p>The big difference between the two implementations is that the
template computation happens at compile-time instead of when the
program is run. Integer results of template computations are
available as compile time constants, for example, in the expression
<tt class="literal">factorial&lt;5&gt;::RET</tt>. This means that,
for example, you could declare an array like this:</p>
<pre class="programlisting">
int buffer[factorial&lt;5&gt;::RET];
</pre>
<p>Types can be manipulated at compile time too, using <tt class=
"literal">typedef</tt> to name intermediate and final results in
the same way that <tt class="literal">enum</tt> (or <tt class=
"type">const int</tt>) is used to name integer values. There's an
example which uses types later in the article.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e172" id="d0e172"></a>The MP
Execution Model</h2>
</div>
<p>If you want to know what happens - in general - when you run a
program in a given language you need to know its <i class=
"firstterm">execution model</i>: a specification of what happens
when a program written in the language is run on a conforming
implementation.</p>
<p>My first acquaintance with the idea of an execution model for MP
was a talk by Gabriel Dos Reis at ACCU 2001 [<a href=
"#Reis2001">Reis2001</a>] in which he showed how C++ template
metaprograms could be modelled in the Scheme language. Scheme is a
good model for MP because both languages' execution models are
essentially those of <span class=
"emphasis"><em>functional</em></span> programming languages.</p>
<p>Dos Reis talked about <span class=
"emphasis"><em>M-values</em></span> (<span class=
"emphasis"><em>M</em></span> stands for <span class=
"emphasis"><em>meta</em></span>) being the MP equivalent to values
in most programming languages. An <span class=
"emphasis"><em>M-value</em></span> is a type or anything else that
can be manipulated at compile time.</p>
<p>AMP <span class="emphasis"><em>M-values</em></span>:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>template instantiation plays the role of a function call</p>
</li>
<li>
<p>template partial specialization provides conditional
branching</p>
</li>
<li>
<p><tt class="literal">enum</tt>s set local aliases for complex
expressions and return integer results</p>
</li>
<li>
<p><tt class="literal">typedef</tt>s set local aliases for complex
types and return type results</p>
</li>
</ul>
</div>
<p>This information is summarized in Table 1.</p>
<div class="table"><a name="d0e226" id="d0e226"></a>
<table summary="AMP Execution Model" border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Feature</th>
<th>MP Implementation</th>
<th>Example Code</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr valign="top">
<td valign="top">conditional branching</td>
<td valign="top">template partial specialization</td>
<td valign="top">
<pre class="programlisting">
template&lt;typename T&gt;
struct Setup { /* code for general case */ };
template&lt;&gt;
struct Setup&lt;Null&gt; { /* code for T==Null */ };
// OR
template&lt;int N&gt;
struct Factorial{ /* code for general case */ };
template&lt;&gt;
struct Factorial&lt;0&gt; { /* code for N==0 */ };
</pre></td>
</tr>
<tr valign="top">
<td valign="top">integer expressions</td>
<td valign="top">enum</td>
<td rowspan="2" valign="top">
<pre class="programlisting">
enum {N=Length&lt;T::Tail&gt;+1};
</pre></td>
</tr>
<tr valign="top">
<td valign="top">set integer alias</td>
<td valign="top">enum</td>
</tr>
<tr valign="top">
<td valign="top">return integer results</td>
<td valign="top">enum</td>
<td valign="top">
<pre class="programlisting">
enum {value=N};
</pre></td>
</tr>
<tr valign="top">
<td valign="top">call MP &quot;functions&quot;</td>
<td valign="top">template instantiation</td>
<td rowspan="2" valign="top">
<pre class="programlisting">
typedef Next&lt;T&gt;::value NextType;
</pre></td>
</tr>
<tr valign="top">
<td valign="top">set type alias</td>
<td valign="top">typedef</td>
</tr>
<tr valign="top">
<td valign="top">return type result</td>
<td valign="top">typedef</td>
<td valign="top">
<pre class="programlisting">
typedef Next&lt;T&gt;::value value;
</pre></td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c2">Table 1. AMP Execution Model</p>
</div>
<p>If you look back to the MP implementation of the factorial
function you will see that it uses features 1, 2 and 3 with these
pieces of code:</p>
<div class="orderedlist">
<ol type="1">
<li>
<pre class="programlisting">
factorial&lt;n-1&gt;::RET
</pre></li>
<li>
<pre class="programlisting">
template&lt;&gt; struct factorial&lt;1&gt;
</pre></li>
<li>
<pre class="programlisting">
enum {RET = 1}
</pre></li>
</ol>
</div>
<p>Using these language features sophisticated programs can be
written (even a Lisp interpreter [<a href=
"#Czarnecki-">Czarnecki-</a>]) but it's not easy: the syntax is
unhelpful and the programs can't be effectively debugged (you can't
single-step through a compilation ...).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e309" id="d0e309"></a>Modelling AMP
in Another Language</h2>
</div>
<p>The C++ MP code in the factorial example and in Listings 1 and 2
can be difficult to follow but the abstract execution model is very
simple. It has <i class="firstterm">single assignment</i>
(variables are initialised on declaration and cannot be modified
thereafter), <i class="firstterm">conditional selection</i>
(choice, as in <tt class="literal">switch</tt> or <tt class=
"literal">if</tt>), but no <i class="firstterm">iteration</i> (no
for, <tt class="literal">while</tt> or <tt class="literal">do</tt>
loops - recursion is used instead).</p>
<p>Given the simplicity of the execution model we can consider
writing programs in a <i class="firstterm">source language</i> with
a more suitable syntax than C++ MP code. Programs written in this
source language could be automatically translated to the correct
C++ MP code.</p>
<p>But which language? A functional language such as Scheme or
Haskell would have the right sort of execution model, but would not
be taken up by many C++ programmers.</p>
<p>Instead I propose that we actually use a subset of C++ itself as
the source language, which I've called <span class=
"bold"><b>typeshift</b></span>. This will by definition be familiar
to C++ programmers and there are other advantages, as we shall
see.</p>
<p>Here's the factorial example in <span class=
"bold"><b>typeshift</b></span> :-</p>
<pre class="programlisting">
int factorial(int n) {
  switch(n) {
    case 1:
      return 1;
    default:
      return n*factorial(n-1);
  }
}
</pre>
<p>It is, of course, the same code as the standard factorial
function we gave earlier (which should be no surprise). This code
is similar but not identical to the factorial function we gave
earlier. It uses <tt class="literal">switch</tt> instead of
<tt class="literal">if</tt> because <span class=
"bold"><b>typeshift</b></span> will not initially support
<tt class="literal">if</tt>.</p>
<p>The point of <span class="bold"><b>typeshift</b></span> is this:
you write a program in the <span class=
"bold"><b>typeshift</b></span> language and then use a translator
to convert it to C++ MP code. The translator would convert the
above factorial program to this MP program (again, this code is
identical to that of the earlier example):</p>
<pre class="programlisting">
// definition
template&lt;int n&gt;
struct factorial {
  enum {RET = n*factorial&lt;n-1&gt;::RET};
};
// partial specialization
template&lt;&gt;
struct factorial&lt;1&gt; {
  enum {RET = 1};
};
</pre>
<p>So now you can write a program in something resembling everyday
C++ and have it converted to a template metaprogram.</p>
<p>Now this is just a tutorial example: a MP factorial program
isn't very practical because it has to be recompiled every time you
want to compute a different factorial. An MP program is only useful
if you can make use of the results of the compile-time computation
when the program is run. Later on we'll look at an admittedly
abstract but genuinely useful example of template
metaprogramming.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e382" id=
"d0e382"></a>typeshift</h2>
</div>
<p><span class="bold"><b>typeshift</b></span> is a <span class=
"emphasis"><em>small</em></span> subset of C++. We take only those
features which are required to support the AMP execution model:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>classes/structs with simple data and function members</p>
</li>
<li>
<p>variable initialisation</p>
</li>
<li>
<p>switch statements</p>
</li>
<li>
<p>return statements</p>
</li>
</ul>
</div>
<p>We do, of course, need to be able to represent types so that we
can support template type-parameters. You might think that this is
where it gets complicated, but in fact it doesn't - in &quot;real&quot; C++
types are very different from values but in typeshift they are
quite similar: everything is just an <span class=
"emphasis"><em>M-value</em></span>.</p>
<p><span class="bold"><b>typeshift</b></span> uses distinguished
identifiers like type, fixed_type and template_type to declare
variables (and subclasses) which to represent types and such
variables behave as they do in MP.</p>
<p>This execution model of AMP as supported by <span class=
"bold"><b>typeshift</b></span> is shown in Table 2 [next page]
which you will want to compare with Table 1. Remember that this is
only the first version of typeshift: over time its syntax and
semantics will be extended to make it even easier to write template
metaprograms.</p>
<p>I have not yet looked into mapping other forms of MP into
<span class="bold"><b>typeshift</b></span> but I hope that we will
only need to add a few more features of C++ to the language for it
to be able to model any current use of MP.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e424" id="d0e424"></a>Typelist
Example</h2>
</div>
<p>Here's an example of MP which uses types. Listings 1 and 2 are
an implementation of the <i class="firstterm">typelist</i>
data-structure from Alexandrescu [<a href=
"#Alexandrescu2001">Alexandrescu2001</a>] (not actually his
implementation). They demonstrate how AMP can be used to implement
a simple <i class="firstterm">type-data- structure</i> (a linked
list of types) and a <i class="firstterm">type-function</i> which
finds the length of such a list.</p>
<div class="sidebar">
<p class="title c2">Listing 1: tm1.h</p>
<pre class="programlisting">
// typelists - standard approach. This
// particular approach even works on MSVC 6.0.

namespace typelists {
  // a list of types, each element has a head
  // and a tail - the head is one of the types
  // in the list, the tail is either another
  // list of types or Null
  template&lt;typename HeadT, typename TailT&gt;
  struct List {
    typedef HeadT Head;
    typedef TailT Tail;
  };

  // terminates type lists
  struct Null {};

  // - find the length of a type list -
  // ... the general case - the length is 1
  // more than the length of the tail
  template&lt;typename T&gt;
  struct Length {
    enum{RET=Length&lt;typename T::Tail&gt;::RET+1};
  };
  // ... the case of Null - the length is zero
  template&lt;&gt;
  struct Length&lt;Null&gt; {
    enum {RET = 0};
  };
};
</pre></div>
<div class="sidebar">
<p class="title c2">Listing 2: tm1.cpp</p>
<pre class="programlisting">
// try out typelists - standard approach
#include &lt;iostream&gt;
#include &quot;tm1.h&quot;
using namespace typelists;

int main() {
  // declare a type list
  typedef List&lt;int, List&lt;double,
              List&lt;char, Null&gt; &gt; &gt; basictypes;
  // compute the length of the type list. the
  // whole right-hand side below is evaluated
  // at compile time (the result is 3)
  int n = Length&lt;basictypes&gt;::RET;
  std::cout &lt;&lt; &quot;n = &quot; &lt;&lt; n &lt;&lt; std::endl;
  return 0;
}
</pre></div>
<p>Listings 3 and 4 [next page] implement the same program, but in
<span class="bold"><b>typeshift</b></span>.</p>
<div class="sidebar">
<p class="title c2">Listing 3: tm2.h</p>
<pre class="programlisting">
// typelists - <span class="bold"><b>typeshift</b></span> approach
#include &lt;ts_runtime.h&gt;

namespace typeshift {
  namespace meta {
    namespace _typelist {

// a list of types, each element has a head
// and a tail - the head is one of the types in
// the list, the tail is either another list of
// types or fixed_type::null
struct List {
  // constructor
  List(const type&amp; HeadT, const type&amp; TailT)
    : Head(HeadT), Tail(TailT) {}
  // members
  const type&amp; Head;
  const type&amp; Tail;
};

// - find the length of a type list -
int Length(const type&amp; T) {
  switch (T) {
  // the case of fixed_type::null - the length
  // is zero
  case fixed_type::null:
    return 0;
  // the general case - the length is 1 more
  // than the length of the tail
  default:
    return Length(dynamic_cast&lt;const
                            List&amp;&gt;(T).Tail)+1;
  }
}
}}};
</pre></div>
<div class="sidebar">
<p class="title c2">Listing 4: tm2.cpp</p>
<pre class="programlisting">
// typelists - try out <span class=
"bold"><b>typeshift</b></span> approach

#include &lt;iostream&gt;
#include &quot;tm2.h&quot;
using namespace typeshift::meta_::typelist;

int main() {
  typedef List&lt;int, List&lt;double,
           List&lt;char, fixed_type::null&gt; &gt; &gt;
           basictypes;
  int n = Length&lt;basictypes&gt;::RET;
        // the generated code still uses RET
  std::cout &lt;&lt; &quot;n = &quot; &lt;&lt; n &lt;&lt; std::endl;
  return 0;
}
</pre></div>
<p>The .h file in Listing 3 is very different from the .h file in
Listing 1 but if you read them while referring to Tables 1 and 2
you should be able to follow how the two sets of code
correspond.</p>
<div class="table"><a name="d0e474" id="d0e474"></a>
<table summary="typeshift Execution Model" border="1" cellspacing=
"0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Feature</th>
<th>typeshift Implementation</th>
<th>Example Code</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr valign="top">
<td valign="top">conditional branching (on types)</td>
<td valign="top">switch</td>
<td valign="top">
<pre class="programlisting">
switch(T) {
  case Null: // code for T==Null
  default: // code for general case
};
// OR
switch(N) {
  case 0: // code for N==0
  default: // code for general case
}
</pre></td>
</tr>
<tr valign="top">
<td valign="top">integer expressions</td>
<td valign="top">expression</td>
<td rowspan="2" valign="top">
<pre class="programlisting">
int N=Length(T.Tail)+1;
</pre></td>
</tr>
<tr valign="top">
<td valign="top">set integer alias</td>
<td valign="top">definition</td>
</tr>
<tr valign="top">
<td valign="top">return integer results</td>
<td valign="top">return</td>
<td valign="top">
<pre class="programlisting">
return N;
</pre></td>
</tr>
<tr valign="top">
<td valign="top">call MP &quot;functions&quot;</td>
<td valign="top">function call syntax</td>
<td rowspan="2" valign="top">
<pre class="programlisting">
type NextType=Next(T);
</pre></td>
</tr>
<tr valign="top">
<td valign="top">set type alias</td>
<td valign="top">type definition</td>
</tr>
<tr valign="top">
<td valign="top">return type result</td>
<td valign="top">return</td>
<td valign="top">
<pre class="programlisting">
return NextType;
</pre></td>
</tr>
&lt;/tbody&gt;
</table>
<p class="title c2">Table 2. typeshift Execution Model</p>
</div>
<p>One important difference between the two sets of code is the
namespace: it was <tt class="literal">typelist</tt> in the original
C++ MP but is <tt class=
"literal">metatypeshift::meta::_typelist</tt> in the <span class=
"bold"><b>typeshift</b></span> code. This is because we propose to
signal the presence of <span class="bold"><b>typeshift</b></span>
code by enclosing it in a distinguished namespace whose name begins
with <tt class="literal">typeshift::meta</tt>, or in a namespace
derived from this. An enhanced C++ compiler or external tool can
use this to pick out the <span class="bold"><b>typeshift</b></span>
code from the &quot;normal&quot; C++ code.</p>
<p>The .cpp file in Listing 4 is practically identical to the .cpp
file in Listing 2 - only the namespace identifier and the name for
the null list-terminator are different. This is because I don't
propose changing the syntax of <span class=
"emphasis"><em>references</em></span> to the names in the generated
C++ MP code (at least, not yet) because that is going to be rather
more difficult to handle than just transforming the <span class=
"emphasis"><em>definition</em></span>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e565" id="d0e565"></a>Coins
Example</h2>
</div>
<p>In [<a href="#Reis2001">Reis2001</a>] Gabriel Dos Reis gives an
example from Abelson &amp; Sussman [<a href=
"#Abelson-1985">Abelson-1985</a>] of a coin-counting program, first
of all in Scheme and then in C++ MP code. Given an amount of money
(in pennies) the program returns the number of ways in which change
can be given using British coins.</p>
<p>Dos Reis's C++ MP code along with a test rig is given in
Listings 5 and 6.</p>
<p>I translated it into <span class="bold"><b>typeshift</b></span>
and this (again, with a test rig) is given in Listings 7 and 8.</p>
<div class="sidebar">
<p class="title c2">Listing 5: coinct.h</p>
<pre class="programlisting">
// coins - C++ MP approach
// This code is reprinted by permission from
// Gabriel Dos Reis' ACCU 2001 talk [<a href=
"#Reis2001">Reis2001</a>]

template&lt;int coin_kind&gt;
struct coin_value { };
template&lt;&gt;
struct coin_value&lt;1&gt; { enum {value = 1}; };
template&lt;&gt;
struct coin_value&lt;2&gt; { enum {value = 5}; };
template&lt;&gt;
struct coin_value&lt;3&gt; { enum {value = 10}; };
template&lt;&gt;
struct coin_value&lt;4&gt; { enum {value = 25}; };
template&lt;&gt;
struct coin_value&lt;5&gt; { enum {value = 50}; };

template&lt;int amount, int coin_kinds, bool stop&gt;
struct count_change_helper {
  enum {remaining_coins = coin_kinds - 1};
  enum {remaining_amount = amount
        - coin_value&lt;coin_kinds&gt;::value};
  enum {value = 
         (count_change_helper&lt;
            remaining_amount, coin_kinds,
            (remaining_amount &lt;= 0 ||
            coin_kinds == 0)&gt;::value
          +
          count_change_helper&lt;
            amount, coin_kinds - 1,
            (amount &lt;= 0 ||
            remaining_coins == 0)&gt;::value)
  };
};

template&lt;int amount, int coin_kind&gt;
struct count_change_helper&lt;amount,
                           coin_kind, true&gt; {
  enum {value = (amount == 0) ? 1 : 0};
};

template&lt;int amount&gt;
struct count_change {
  enum {value = count_change_helper&lt;amount, 5,
        (amount &lt;= 0 || 5 == 0)&gt;::value };
};
</pre></div>
<div class="sidebar">
<p class="title c2">Listing 6: coinct.cpp</p>
<pre class="programlisting">
// coins - try C++ MP approach
#include &quot;coinsct.h&quot;
#include &lt;iostream&gt;
int main() {
const int amount = 23;
std::cout &lt;&lt; &quot;ways for &quot; &lt;&lt; amount &lt;&lt; &quot;: &quot;
&lt;&lt; count_change&lt;amount&gt;::value &lt;&lt; std::endl;
return 0;
};

template&lt;int amount, int coin_kind&gt;
struct count_change_helper&lt;amount,
                           coin_kind, true&gt; {
  enum {value = (amount == 0) ? 1 : 0};
};

template&lt;int amount&gt;
struct count_change {
  enum {value = count_change_helper&lt;amount, 5,
        (amount &lt;= 0 || 5 == 0)&gt;::value };
};
</pre></div>
<div class="sidebar">
<p class="title c2">Listing 7: coinrt.h</p>
<pre class="programlisting">
// coins - <span class="bold"><b>typeshift</b></span> approach
#include &lt;ts_runtime.h&gt;
namespace typeshift {
namespace meta {
namespace coins {
int coin_value(int coin_index) {
switch (coin_index) {
case 1: return 1;
case 2: return 5;
case 3: return 10;
case 4: return 25;
case 5: return 50;
}
}
int count_change_helper(int amount,
int coin_kinds, bool stop) {
switch (stop) {
case true:
return (amount==0)?1:0;
case false: {
int remaining_coins = coin_kinds - 1;
int remaining_amount =
amount - coin_value(coin_kinds);
int value = count_change_helper(
remaining_amount, coin_kinds,
remaining_amount &lt;= 0 ||
coin_kinds == 0)
+
count_change_helper(amount,
coin_kinds - 1, amount &lt;= 0 ||
remaining_coins == 0);
return value;
}
}
}
int count_change(int amount) {
int value = count_change_helper(amount, 5,
amount &lt;= 0 || 5 == 0);
return value;
}
}}}
</pre></div>
<div class="sidebar">
<p class="title c2">Listing 8: coinrt.cpp</p>
<pre class="programlisting">
// coins - try typeshift approach
#include &quot;coinsrt.h&quot;
#include &lt;iostream&gt;
#include &lt;sstream&gt;
int main() {
const int amount = 23;
std::cout &lt;&lt; &quot;ways for &quot; &lt;&lt; amount &lt;&lt; &quot;: &quot;
&lt;&lt; typeshift::meta::coins::count_change(amount)
&lt;&lt; std::endl;
return 0;
}
template&lt;int amount, int coin_kind&gt;
struct count_change_helper&lt;amount,
                           coin_kind, true&gt; {
  enum {value = (amount == 0) ? 1 : 0};
};

template&lt;int amount&gt;
struct count_change {
  enum {value = count_change_helper&lt;amount, 5,
        (amount &lt;= 0 || 5 == 0)&gt;::value };
};
</pre></div>
<p>If you compare the two sets of listings I think you will agree
that the <span class="bold"><b>typeshift</b></span> version is
clearer. But there's more - <span class=
"bold"><b>typeshift</b></span> is a subset of C++ so we can
actually compile and run a <span class=
"bold"><b>typeshift</b></span> program <span class=
"emphasis"><em>without</em></span> translating it to C++ MP
code.</p>
<p>Both programs can be built<sup>[<a name="d0e625" href=
"#ftn.d0e625" id="d0e625">2</a>]</sup> with gcc 2.91.66. When
compiling the C++ MP code pass <tt class=
"literal">-ftemplate-depth-99</tt> to g++ to maximise the size of
the problem that can be handled.</p>
<p>When run with the same input the programs give identical results
so they are in some sense operationally equivalent. However, the
C++ MP code computes the answer at <span class=
"emphasis"><em>compile-time</em></span> but the <span class=
"bold"><b>typeshift</b></span> code computes the answer at
<span class="emphasis"><em>run-time</em></span>.</p>
<p>This operational equivalence means that metaprograms can be
written in <span class="bold"><b>typeshift</b></span> and tested
and debugged in the value-domain. Only then need the program be
transformed to C++ MP code for execution at compilation time.</p>
<p>Even <span class="bold"><b>typeshift</b></span> programs that
use <span class="emphasis"><em>types</em></span> can be compiled,
run and debugged in this way using the <span class=
"bold"><b>typeshift</b></span> '<tt class="literal">type</tt>'
class library.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e662" id=
"d0e662"></a>Implementation</h2>
</div>
<p>There are two ways of implementing <span class=
"bold"><b>typeshift</b></span>:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>by extending a C++ compiler</p>
</li>
<li>
<p>by writing an external tool</p>
</li>
</ul>
</div>
<p>A C++ compiler essentially already has the mechanism to compile
typeshift because syntactically and semantically it is a true
subset of C++. Two changes would be needed:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Only a subset of C++ features are allowed in <span class=
"bold"><b>typeshift</b></span> so the standard parser would need to
be adapted to handle this restricted &quot;dialect&quot;.</p>
</li>
<li>
<p>The <span class="bold"><b>typeshift</b></span> code needs to be
transformed into the C++ MP code before it is compiled in the
normal way. This is a fairly straightforward transformation.</p>
</li>
</ul>
</div>
<p>There should be no impact on compilation outside the <tt class=
"literal">typeshift::meta_xxx</tt> namespace because from the point
of view of code outside the namespace the names defined inside the
namespace are from the transformed C++ code. It is not possible for
code outside the namespace to &quot;have any knowledge of&quot; the original
<span class="bold"><b>typeshift</b></span> code.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e700" id=
"d0e700"></a>Implementation by an External Tool</h2>
</div>
<p>A proof-of-concept <span class="bold"><b>typeshift</b></span>
pre-processor is currently under development, and should be
available from <a href="http://www.typeshift.org" target=
"_top">http://www.typeshift.org</a> when this article is published.
It will be downloadable in the form of source code for a C++
program released under the GPL (GNU General Public License
[<a href="#GPL">GPL</a>]).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e714" id=
"d0e714"></a>Conclusion</h2>
</div>
<p>Template metaprogramming has traditionally been viewed as an
esoteric and obscure area of C++, but using <span class=
"bold"><b>typeshift</b></span> metaprograms can now be written (and
even debugged) in a familiar language. Hopefully this will lead to
metaprogramming being used much more widely in C++.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e722" id=
"d0e722"></a>Acknowledgements</h2>
</div>
<p>Many thanks to Gabriel Dos Reis for his advice and
encouragement, and also for his permission to quote the example
program from [<a href="#Reis2001">Reis2001</a>].</p>
<p>Thanks too to Mark Radford for his invaluable comments and
suggestions, which have certainly made the article easier to
understand.</p>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e732" id="d0e732"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Veldhuizen1995" id=
"Veldhuizen1995"></a>
<p class="bibliomixed">[Veldhuizen1995] Veldhuizen, 1995: Template
Metaprograms (<span class="bibliomisc"><a href=
"http://www.osl.iu.edu/~tveldhui/papers/Template-Metaprograms/meta-art.html"
target=
"_top">http://www.osl.iu.edu/~tveldhui/papers/Template-Metaprograms/meta-art.html</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Walker2001" id="Walker2001"></a>
<p class="bibliomixed">[Walker2001] Walker, 2001: &quot;Template
Metaprogramming: make your compiler work for you&quot; <span class=
"citetitle"><i class="citetitle">Overload 46</i></span></p>
</div>
<div class="bibliomixed"><a name="Blitz" id="Blitz"></a>
<p class="bibliomixed">[Blitz] Blitz (<span class=
"bibliomisc"><a href="http://www.oonumerics.org/blitz/whatis.html"
target=
"_top">http://www.oonumerics.org/blitz/whatis.html</a></span>)</p>
</div>
<div class="bibliomixed"><a name="GMCL" id="GMCL"></a>
<p class="bibliomixed">[GMCL] Generative Matrix Computation Library
(<span class="bibliomisc"><a href=
"http://wwwia.tu-ilmenau.de/~czarn/gmcl/" target=
"_top">http://wwwia.tu-ilmenau.de/~czarn/gmcl/</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Attardi-" id="Attardi-"></a>
<p class="bibliomixed">[Attardi-] Giuseppe Attardi, Antonio
Cisternino: Reflection support by means of template metaprogramming
(<span class="bibliomisc"><a href=
"http://citeseer.nj.nec.com/451721.html" target=
"_top">http://citeseer.nj.nec.com/451721.html</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Barton-" id="Barton-"></a>
<p class="bibliomixed">[Barton-] John J. Barton, Lee R. Nackman:
&quot;Scientific and Engineering C++: Dimensional Analysis&quot; <span class=
"citetitle"><i class="citetitle">C++ Report</i></span>, vol 7 p39,
Jan. 1995</p>
</div>
<div class="bibliomixed"><a name="Breymann-" id="Breymann-"></a>
<p class="bibliomixed">[Breymann-] Ulrich Breymann, Krzysztof
Czarnecki, Ulrich Eisenecker: Generative Components: One Step
Beyond Generic Programming (<span class="bibliomisc"><a href=
"http://home.t-online.de/home/Ulrich.Eisenecker/dag.htm" target=
"_top">http://home.t-online.de/home/Ulrich.Eisenecker/dag.htm</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Unruh1994" id="Unruh1994"></a>
<p class="bibliomixed">[Unruh1994] Unruh, 1994: Prime number
computation (ANSI X3J16-94-0075/ISO WG21-462)</p>
</div>
<div class="bibliomixed"><a name="Alexandrescu2001" id=
"Alexandrescu2001"></a>
<p class="bibliomixed">[Alexandrescu2001] Alexandrescu, 2001:
<span class="citetitle"><i class="citetitle">Modern C++
Design</i></span> (Addison-Wesley, ISBN 0-201-70431-5)</p>
</div>
<div class="bibliomixed"><a name="Reis2001" id="Reis2001"></a>
<p class="bibliomixed">[Reis2001] Dos Reis, 2001: <span class=
"citetitle"><i class="citetitle">Metaprogramming in C++</i></span>
(<span class="bibliomisc"><a href=
"http://www.cmla.ens-cachan.fr/~dosreis/C++/" target=
"_top">http://www.cmla.ens-cachan.fr/~dosreis/C++/</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Czarnecki-" id="Czarnecki-"></a>
<p class="bibliomixed">[Czarnecki-] Czarnecki, Eisenecker:
metalisp.cpp (<span class="bibliomisc"><a href=
"http://home.t-online.de/home/Ulrich.Eisenecker/meta.htm" target=
"_top">http://home.t-online.de/home/Ulrich.Eisenecker/meta.htm</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Abelson-1985" id=
"Abelson-1985"></a>
<p class="bibliomixed">[Abelson-1985] Abelson and Sussman, 1985:
Structure and Interpretation of Computer Programs (<span class=
"bibliomisc"><a href="http://mitpress.mit.edu/sicp" target=
"_top">http://mitpress.mit.edu/sicp</a></span>)</p>
</div>
<div class="bibliomixed"><a name="GPL" id="GPL"></a>
<p class="bibliomixed">[GPL] GNU General Public License
(<span class="bibliomisc"><a href=
"http://www.gnu.org/licenses/gpl.html#SEC1" target=
"_top">http://www.gnu.org/licenses/gpl.html#SEC1</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Reis2002" id="Reis2002"></a>
<p class="bibliomixed">[Reis2002] Dos Reis, 2002: (personal
communication)</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e110" href="#d0e110" id=
"ftn.d0e110">1</a>]</sup> The historical use of <tt class=
"literal">enum</tt> in this context was originally a workaround for
compiler limitations. On a compiler that supports the latest
version of the standard &quot;<tt class="literal">const int RET =
1;</tt>&quot; is not only perfectly legal, but perhaps a more idiomatic
usage</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e625" href="#d0e625" id=
"ftn.d0e625">2</a>]</sup> MSVC6 won't compile the C++ MP program
because it does not support partial template specialisation (I have
not tried MSVC7)</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
