    <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  :: C++ Templates</title>
        <link>https://members.accu.org/index.php/journals/2014</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 #53 - Feb 2003 + Programming Topics</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/c193/">53</a>
                    (9)
<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/c193-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c193+65/">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;C++ Templates</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 01 February 2003 07:06:54 +00:00 or Sat, 01 February 2003 07:06:54 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<p>If you wanted to know just about everything about C++ templates then the book <em>C++ Templatesâ€”The Complete Guide</em> by David Vandevoorde and Nicolai Josuttis, (ISBN 0-201-73484-2) is a readable reference book you can use. Normally, discussing a book would appear in a book review. However, since the authors have done such a good job of describing C++ templates, I though the topic and the book deserved more complete coverage. You may recall Nicolai as the author of the excellent text, <em>The C++ Standard Library</em>, ISBN 0-201-37926-0. David is the author of <em>C++ Solutions: Companion to the C++ Programming Language , Third Edition</em>, ISBN 0-201-30965-3. Both authors are also longtime members of the ANSI/ISO C++ X3J16 Standardization Committee.</p>
<h2>Ordering Convention</h2>
<p>Most of us write the following <code>const</code> or <code>volatile</code> declaration thus:</p>
<pre><code>volatile int vInt;
const char *pcChar;
</code></pre>

<p>The authors suggest that a better way is:</p>
<pre><code>int volatile vInt;  // 1
char const *pcChar; // 2
</code></pre>

<p>Here, <code>const</code> and <code>volatile</code> appear before what they qualify. Since I read declarations from right to left, in //1, I get <code>vInt</code> is a volatile int and in //2, I get <code>pcChar</code> is a pointer to a <code>const</code> char. The real power comes when we use this ordering in <code>typedef</code> statements. For example,</p>
<pre><code>typedef int *PINT;
typedef PINT const CPINT;
typedef const PINT PCINT;
</code></pre>

<p>Here we can see that the first <code>typedef</code> (pointer to int) can be used in the second <code>typedef</code> (<code>const</code> pointer to <code>int</code>). The third <code>typedef</code> completely changes the meaning of the type (pointer to <code>const int</code>).</p>
<h2><code>typename</code> Keyword</h2>
<p>Historically, we have used the keyword, <code>class</code>, in template parameter lists:</p>
<pre><code>template&lt; class T &gt; . . .
</code></pre>

<p>However, T could be replaced by things other than a class name, so the use of the new keyword <code>typename</code> is preferred.</p>
<h2>Reducing Ambiguities</h2>
<p>Often, instantiating a template can result in an ambiguity error that is difficult to understand. Here is a simple example:</p>
<pre><code>template&lt; typename T &gt; plot2D(T&amp; x, T&amp; y);
plot2D(3,4);    // ok
plot2D(3.14,1); // error - types of arguments differ
</code></pre>

<p>The ambiguity occurs because all parameters are supposed to be of same type, but in the second case, it is unclear whether that type should be an <code>int</code> or a <code>double</code>.</p>
<p>In this simple example (and many others like it), there are 3 ways of disambiguating the statement:</p>
<pre><code>plot2D&lt;int&gt;(3.14,1);                // 3
plot2D(static_cast&lt;int&gt;(3.14), 1);  // 4
</code></pre>

<p>In //3, the template type is forced to be <code>int</code>. In //4, casting forces all the argument types to be the same. The third way to eliminate this problem uses more sophisticated templates.</p>
<h2>Overloading function template</h2>
<p>It is possible to have both template and non-template versions of the same function. Often, non-template versions are called specializations. In such situations, function overloading and its rules are used to resolve any ambiguities. In addition to normal function overloading rules, a few extra rules are needed for templates.</p>
<ul>
<li>
<p>In instantiating a template function, no type conversions are done.</p>
</li>
<li>
<p>All things being equal, specialized template functions are preferred over template ones.</p>
</li>
<li>
<p>If instantiating a template function results in a better match, the better match is used. By better match, we mean that things like conversions are not need to make a match.</p>
</li>
<li>
<p>If the empty angle brackets notation is used, non-template functions are ignored in matching argument. </p>
</li>
</ul>
<p>Here are some examples:</p>
<pre><code>int cmp(int const&amp; a, int const&amp; b);
template&lt;typename T&gt; T cmp(T const&amp; a, T const &amp;b);
cmp(1,2);           // 5
cmp(4.3, -1.2);     // 6
cmp('x','s');       // 7
cmp&lt;&gt;(-3,2);        // 8
cmp&lt;int&gt;(4.3,4);    // 9
</code></pre>

<p>In //5, the non-template function is the best match (Rule 2). In //6, template argument deduction instantiates the <code>cmp&lt;double&gt;</code> function (Rule 3). In //7, the instantiated function is <code>cmp&lt;char&gt;</code> (Rule 3). In //8, the notation forces use of the template function and results in a <code>cmp&lt;int&gt;</code> function being instantiated and used instead of the non-template version of the <code>cmp</code> function (Rule 4).</p>
<h2>Partial Specialization</h2>
<p>When a template class or function has more than one template parameter, one or more may be specified creating a partially specialized template. However, if one or more partial specializations match the same template, an ambiguity occurs. For example,</p>
<pre><code>#include &lt;typeinfo&gt;
#include &lt;stdio.h&gt;
typedef char const CC;

// general template function

template&lt;typename T1,typename T2&gt;
void f(T1 t1, T2 t2) {
    CC* s1=typeid(T1).name();
    CC* s2 = typeid(T2).name();
    printf(&quot;f(%s,%s)\n&quot;,s1,s2);

}

// partial specialization 1
// both types the same

template&lt;typename T&gt;
void f(T t1, T t2) {
    CC* s1 = typeid(T).name();
    CC* s2 = typeid(T).name();
    printf(&quot;f1(%s,%s)\n&quot;,s1,s2);

}

// partial specialization 2
// 2nd parameter is non-type

template&lt; typename T&gt;
void f(T t1, int t2) {
    CC* s1 = typeid(T).name();
    CC* s2 = typeid(int).name();
    printf(&quot;f(%s,%s)\n&quot;,s1,s2);

}

// partial specialization 3
// parameters are all pointers

template&lt; typename T1, typename T2&gt;
void f(T1* t1, T2* t2) {
    CC* s1 = typeid(T1*).name();
    CC* s2 = typeid(T2*).name();
    printf(&quot;f(%s,%s)\n&quot;,s1,s2);

}

int main(int argc,char* argv[]) {
    char const* s1=â€oneâ€;
    f(1,21.3);
    f(1.2,-3);
    f('a','z');
    f(s1,2);
    f(&amp;s1,&quot;two&quot;);
    return 0;
}
</code></pre>

<p>The output from this program is:</p>
<pre><code>f(int,double)
f(double,int)
f(char,char)
f(CC *,int)
f(CC **,char *)
</code></pre>

<p>Note that calling f(3,5) is ambiguous because both <code>f(T,T)</code> and <code>f(T,int)</code> match this call.</p>
<h2>Non-type Template Parameters</h2>
<p>Both classes and functions can use non-type template parameters. When used, non-type parameters become part of the classes type and functions signature. Thus,</p>
<pre><code>template&lt;typename T, int n&gt;
class C {
    T a[n];
    // . . .
};
C&lt;char, 10&gt; c10A;
C&lt;char, 5&gt; c5A;
C&lt;int, 10&gt; i10A;
</code></pre>

<p>Each of <code>c10A</code>, <code>c5A</code>, and <code>i10A</code> are all distinct types. </p>
<p>An example of a template function using non-type parameter follows:</p>
<pre><code>template&lt;typename T, int n&gt;
T g(T t) {
    return t+n;
}

int main() {
    printf(&quot;g&lt;double,5&gt;(1.3)=%g\n&quot;, g&lt;double,5&gt;(1.3));
    printf(&quot;g&lt;char,4&gt;(â€˜aâ€™)=%c\n&quot;, g&lt;char,4&gt;(â€˜aâ€™));
}
</code></pre>

<p>The output of this short program is:</p>
<pre><code>g&lt;double,5&gt;(1.3)=6.3
g&lt;char,4&gt;('a')=e
</code></pre>

<p>Non-type template parameters have restrictions: they must be integral values, enumerations, or instance pointers with external linkage. They canâ€™t be string literals nor global pointers since both have internal linkage.</p>
<h2>Keyword <code>typename</code></h2>
<p>You may have wondered why we needed the new keyword <code>typename</code>. Besides being a better choice for template parameters, it is needed to disambiguate certain declarations. E.g.,</p>
<pre><code>template&lt;typename T, int n&gt;
class C {
    typename T::X *p;
    // . . .
};
</code></pre>

<p>Without the keyword <code>typename</code>, the declaration for p becomes an expression: the value of <code>T::X</code> is multiplied by the value of <code>p</code>.</p>
<p>Generally, prefix all declarations using template parameters with <code>typename</code>.</p>
<h2>this pointer</h2>
<p>Normally derived and base classes share the value of <code>this</code>. However, lookup rules for template classes are different. Template base class members are not lookup when searching derived template class member functions.</p>
<pre><code>template&lt;typename T&gt;
class B {
    void foo();
}

template&lt;typename T&gt;
class D: public B&lt;T&gt; {
    void bar() { foo(); }
}
</code></pre>

<p>In <code>bar()</code>, <code>foo()</code> would not be found. To get <code>B</code>â€™s foo, you need to say <code>this-&gt;foo()</code>. Again, the rule given in the book states that any base class member used in a derived class should be qualified by <code>this-&gt;</code> or <code>B&lt;T&gt;::</code>.</p>
<h2>Conclusion</h2>
<p>I have not begun to cover many of the interesting aspects of templates in this short article. And I have barely covered the other fun parts of this book. Get it.</p>
<p>Reg Charney</p>
<p>This article was originally published on the ACCU USA website in December 2002 at http://www.accu-usa.org/2002-12.html</p>
<p>Thanks to Reg for allowing us to reprint it.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
