    <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  :: Introduction to C++ Templates</title>
        <link>https://members.accu.org/index.php/articles/427</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 #45 - Oct 2001</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/c159/">45</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+159/">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;Introduction to C++ Templates</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 October 2001 17:46:07 +01:00 or Fri, 26 October 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>C++ templates are a powerful mechanism for code reuse, as they
enable the programmer to write code that behaves the same for data
of any type. Suppose you write a function printData:</p>
<pre class="programlisting">
void printData(int value) {
   std::cout &lt;&lt; &quot;The value is &quot; &lt;&lt; value &lt;&lt; std::endl;
}
</pre>
<p>If you later decide you also want to print <tt class=
"literal">double</tt> values, or <tt class=
"literal">std::string</tt> values, then you have to overload the
function:</p>
<pre class="programlisting">
void printData(double value) {
   std::cout &lt;&lt; &quot;The value is &quot; &lt;&lt; value &lt;&lt; std::endl; 
} 
void printData(std::string value) {
   std::cout &lt;&lt; &quot;The value is &quot; &lt;&lt; value &lt;&lt; std::endl; 
}
</pre>
<p>The actual code written for the function is identical in each
case; it is just the type of the variable <tt class=
"literal">value</tt> that changes, yet we have to duplicate the
function for each distinct type. This is where templates come in -
they enable the user to write the function once for any type of the
variable <tt class="literal">value</tt>.</p>
<pre class="programlisting">
template&lt;typename T&gt; void printData(T value) {
   std::cout &lt;&lt; &quot;The value is &quot; &lt;&lt; value &lt;&lt; std::endl; 
}
</pre>
<p>That's all there is to it1 - we can now use <tt class=
"literal">printData</tt> for any data that can be written to a
<tt class="literal">std::ostream</tt>. Here, the <tt class=
"literal">template&lt;typename T&gt;</tt> part tells the compiler
that what follows is a template, and that <tt class=
"literal">T</tt> is a template parameter that identifies a type.
Then, anywhere in the function where <tt class="literal">T</tt>
appears, it is replaced with whatever type the function is
instantiated for - e.g.:</p>
<pre class="programlisting">
int i=3; 
double d=4.75; 
std::string s(&quot;hello&quot;); 
bool b=false; 
printData(i); // T is int 
printData(d); // T is double 
printData(s); // T is std::string 
printData(b); // T is bool
</pre>
<p>It is possible to write class templates as well as function
templates like <tt class="literal">printData</tt>. A common example
is <tt class="literal">std::vector</tt> - you can specify a vector
of integers, or of strings, or of some user-defined class, simply
by specifying the template parameter:</p>
<pre class="programlisting">
class MyClass{}; 
std::vectorint vi; // contains ints 
std::vectordouble vd; // contains doubles 
std::vectorstd::string vs; // contains std::strings 
std::vectorMyClass vmc; // contains MyClass objects 
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e73" id="d0e73"></a>Defining
Templates</h2>
</div>
<p>A Template Definition starts with the keyword template, followed
by a list of <a href="#TemplateParameters">Template Parameters</a>.
What follows is then either a class definition, or a function
definition, defining a class template or a function template
respectively.</p>
<p>The template parameters introduce names into the scope of the
definition, which can be types, values or templates. These names
can be used just like any other name of the same kind. Then, when
the template is instantiated, real types, values or templates are
substituted in place of these names, and the code compiled.</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e83" id="d0e83"></a><span><a name=
"TemplateParameters" id="TemplateParameters"></a>Template
Parameters</span></h2>
</div>
<p>Templates can have one or more template parameters, which can
be:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Type parameters (<a href="#TemplateTypeParameters">Template Type
Parameters</a>) (such as those in the introduction),</p>
</li>
<li>
<p>Non-Type parameters (<a href=
"#TemplateNonTypeParameters">Template Non-Type Parameters</a>)
(e.g. an integer), or</p>
</li>
<li>
<p>Template parameters (<a href=
"#TemplateTemplateParameters">Template Template
Parameters</a>).</p>
</li>
</ul>
</div>
<p>Two template instantiations refer to the same template if their
parameters are all the same, irrespective of any <tt class=
"literal">typedef</tt>s that may apply. Therefore <tt class=
"literal">vec1</tt>, <tt class="literal">vec2</tt> and <tt class=
"literal">vec3</tt> in the following example are all the same
type.</p>
<pre class="programlisting">
typedef std::string MyString; typedef std::vectorstd::string T1; typedef std::vectorMyString T2; T1 vec1; T2 vec2; std::vectorstd::string vec3;
</pre>
<p>Multiple parameters may be specified, separated by commas in the
template parameter list:</p>
<pre class="programlisting">
templatetypename T1,typename T2 class MyClass{}; 
</pre>
<p><tt class="literal">MyClass</tt> is thus a class template with
two template type parameters, <tt class="literal">T1</tt> and
<tt class="literal">T2.</tt></p>
<p>Every time a template is referenced with distinct template
arguments, then the template is instantiated with the arguments
substituted as explained in the following sections. If the
resultant code is not valid, then a compilation error will
occur.</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e139" id=
"d0e139"></a><span><a name="TemplateTypeParameters" id=
"TemplateTypeParameters"></a>Template Type Parameters</span></h2>
</div>
<p>Template Type Parameters are template parameters that refer to a
type; they are the most common form of template parameters. The
template parameter for printData in the introduction <sup>[<a name=
"d0e145" href="#ftn.d0e145" id="d0e145">1</a>]</sup> is an example
of a template type parameter. The syntax is simple:</p>
<pre class="programlisting">
typename name
</pre>
<p>or</p>
<pre class="programlisting">
class name
</pre>
<p>Both alternatives are identical in meaning, and the choice is
merely a matter of style. name is any valid C++ symbol name. Once
name has been introduced in the template parameter list, then any
reference to name within the body of the template automatically
refers to the type of the corresponding template argument for each
instantiation, and can be used anywhere a type can normally be
used. e.g.</p>
<pre class="programlisting">
template&lt;typename T&gt; void func(T value) { const T&amp; ref=value; T* p=new T; T temp(23); }
</pre>
<p>The code generated for <tt class="literal">func&lt;int&gt;</tt>
is then identical to:</p>
<pre class="programlisting">
void func(int value) { const int&amp; ref=value; int* p=new int; int temp(23); }
</pre>
<p>If, however, a reference was made to <tt class=
"literal">func&lt;std::string&gt;</tt>, then a compilation error
would result, as the statement</p>
<pre class="programlisting">
std::string temp(23);
</pre>
<p>is not valid.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e180" id=
"d0e180"></a><span><a name="TemplateNonTypeParameters" id=
"TemplateNonTypeParameters"></a>Template Non-Type
Parameters</span></h2>
</div>
<p>Non-Type Template Parameters are template parameters that are
values rather than types. They can be any value that is a
compile-time constant<sup>[<a name="d0e186" href="#ftn.d0e186" id=
"d0e186">2</a>]</sup>.Their syntax is akin to a variable
declaration, e.g.:</p>
<pre class="programlisting">
template&lt;int i&gt; class A{}; template&lt;double* dp&gt; class B{}; template&lt;void (*func)(int)&gt; void c() {}
</pre>
<p>Class template <tt class="literal">A</tt> has a non-type
template parameter which is an integer, class template <tt class=
"literal">B</tt> has a non-type template parameter which is a
pointer-to-double, and function template <tt class="literal">c</tt>
has a non-type template parameter which is a pointer to a function
returning <tt class="literal">void</tt>, with a single <tt class=
"literal">int</tt> parameter. Examples of uses are:</p>
<pre class="programlisting">
A3 a3; A&lt;sizeof(std::string)&gt; as; double d; // at global scope B&lt;&amp;d&gt; bpd; B&lt;NULL&gt; bn; void myfunc(int); struct MyClass { static void staticFunc(int); }; int main() { c&lt;&amp;myfunc&gt;(); c&lt;&amp;MyClass::staticFunc&gt;(); }
</pre>
<p>Within the definition of a template, the names of a non-type
template parameter refers to a constant of the appropriate type, so
given</p>
<pre class="programlisting">
template&lt;int i&gt; void func() { std::cout&lt;&lt;i&lt;&lt;std::endl; }
</pre>
<p><tt class="literal">func&lt;3&gt;()</tt> will print 3, and
<tt class="literal">func&lt;999&gt;()</tt> will print 999.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e222" id=
"d0e222"></a><span><a name="TemplateTemplateParameters" id=
"TemplateTemplateParameters"></a>Template Template
Parameters</span></h2>
</div>
<p>Template Template Parameters enable a template to be
parameterized by the name of another template. Say, for example,
that you have a class which contains a couple of collections of
items, some strings, some integers, and you want the users of your
class to choose what type of collection to use (vector, list,
stack, etc.). The natural thought is to make the collection type a
template parameter. However, a collection of strings is a different
type from a collection of integers, so the user would have to
specify both individually if <a href=
"#TemplateTypeParameters">Template Type Parameters</a> are used.
The solution is a Template Template Parameter:</p>
<pre class="programlisting">
template&lt;template&lt;typename T&gt; class ContainerType&gt; class MyClass { ContainerType&lt;int&gt; intContainer; ContainerType&lt;std::string&gt; stringContainer; // rest of class };
</pre>
<p><tt class="literal">ContainerType</tt> is a Template Template
Parameter that refers to a template with a single Template Type
Parameter. You can thus say <tt class=
"literal">MyClass&lt;vector&gt;</tt> or <tt class=
"literal">MyClass&lt;list&gt;</tt> to have <tt class=
"literal">vector</tt>s or <tt class="literal">list</tt>s
respectively<sup>[<a name="d0e249" href="#ftn.d0e249" id=
"d0e249">3</a>]</sup>.</p>
<p>Within the template definition, the Template Template Parameters
can be used just like any other template.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e255" id=
"d0e255"></a><span><a name="DefaultTemplateParameters" id=
"DefaultTemplateParameters"></a>Default Template
Parameters</span></h2>
</div>
<p>Just as functions can have default values for their arguments,
so can templates - indeed, this facility works in pretty much the
same way. If a template parameter has a default specified, then all
subsequent template parameters must also have a default specified.
When referencing a template, parameters with default values can be
omitted; if a template parameter is omitted, all subsequent
template parameters must also be omitted. e.g.</p>
<pre class="programlisting">
template&lt;class T1, class T2=int, int i=23&gt; class MyClass{}; // specify all parameters MyClass&lt;double,std::string,46&gt; mc1; // omit &quot;i&quot; MyClass&lt;std::string,double&gt; mc2; // same as above MyClass&lt;std::string,double,23&gt; mc3; // all default MyClassint mc4; // we must specify &quot;T2&quot; if we wish to // specify &quot;i&quot; MyClass&lt;int,int,0&gt; mc5; 
</pre>
<p>The syntax for declaring a default value for a template
parameter is simple just add &quot;= default-value&quot; to the parameter
declaration, as shown in the example. If a template parameter is
omitted when referencing the template, then the default value is
substituted instead.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e265" id=
"d0e265"></a><span><a name="DependentNames" id=
"DependentNames"></a>Dependent Names</span></h2>
</div>
<p>A Dependent Name is any name within a template definition that
depends on one or more of the template parameters. This includes
the template parameters themselves and other templates instantiated
with template arguments that are dependent names in the current
expansion. Dependent names are important, because they are only
resolved when the template is instantiated. As a consequence of
this, dependent names that are members of types that are themselves
dependent names are always assumed to name objects or functions
rather than types, unless preceded with the typename keyword.
e.g.</p>
<pre class="programlisting">
struct X { int x; typedef double Z; }; struct Y { typedef int x; double Z; }; template&lt;typename T&gt; struct ZZ { T::Z z1; // 1 typename T::Z z2; // 2 void func(T&amp; t) { t.x=4; // 3 } typedef typename std::vector&lt;T&gt;::iterator VecIt; // 4 }; int main() { X x; Y y; ZZX zzx; // 5 ZZY zzy; // 6 zzx.func(x); // 7 zzy.func(y); // 8 } 
</pre>
<p>The line marked 1 is illegal, as <tt class="literal">T::Z</tt>
is assumed to refer to an object or function rather than a type.
Line 2 is the correct way of doing things. At line 3, <tt class=
"literal">t.x</tt> is a dependent name, but it refers to an object
so this is OK. At line 4, <tt class=
"literal">std::vector&lt;T&gt;::iterator</tt> is a dependent name
that refers to a type, so we need the <tt class=
"literal">typename</tt> keyword. Lines 5 and 6 instantiate the
template for the types <tt class="literal">X</tt> and <tt class=
"literal">Y</tt>. Line 5 is OK, because <tt class=
"literal">X::Z</tt> is a type, but line 6 is not, as <tt class=
"literal">Y::Z</tt> is an object. Lines 7 and 8 demonstrate the
opposite - <tt class="literal">X::x</tt> is OK because it is an
object, but <tt class="literal">Y::x</tt> is a type, so the
instantiation of <tt class="literal">ZZ&lt;Y&gt;::func</tt> will
fail.</p>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e308" id=
"d0e308"></a><span><a name="UsingTemplates" id=
"UsingTemplates"></a>Using Templates</span></h2>
</div>
<p>Class templates and function templates can be used anywhere
normal classes and functions can be, as well as <a href=
"#TemplateTemplateParameters">Template Template Parameters</a> to
other templates. However, the compiler needs to know what to use
for the template parameters.</p>
<p>For class templates, the template name must be followed by a
template argument list, specifying the parameters. This is a
comma-separated list of expressions between angle brackets
(&lt;&gt;). For Template Type Parameters, the corresponding
expression must name a type, for Template Non-Type Parameters, the
expression must evaluate to a compile-time constant of the
appropriate type, and for Template Template Parameters, the
expression must name a template with the correct signature.
e.g.:</p>
<pre class="programlisting">
template&lt;typename T,unsigned i&gt; struct FixedArray { T data[i]; }; FixedArray&lt;int,3&gt; a; // array of 3 integers FixedArray&lt;int,1+6/3&gt; b; // array of 3 integers template&lt;template&lt;typename T, typename Allocator&gt; class Container&gt; struct ContainerPair { Container&lt;int,std::allocator&lt;int&gt; intContainer; Container&lt;std::string,std:: allocator&lt;std::string&gt; &gt; stringContainer; }; ContainerPair&lt;std::deque&gt; deqCont; // two std::deques ContainerPair&lt;std::vector&gt; vecCont; // two std::vectors
</pre>
<p>The second example demonstrates two things. Firstly, the
template signature of the <a href=
"#TemplateTemplateParameters">Template Template Parameters</a> must
exactly match the signature of the template passed as the argument,
and standard containers have two template parameters. Secondly, if
the last argument of a template parameter list is a template
reference, as for <tt class=
"literal">Container&lt;int,std::allocator&lt;int&gt; &gt;</tt> ,
then the two closing angle brackets (<tt class="literal">&gt;</tt>)
must be separated by a space, to avoid being interpreted as the
shift right operator (<tt class="literal">&gt;&gt;</tt>).</p>
<p>For function templates, there are two options for specifying the
template parameters. Firstly, the function name can be followed by
a template argument list as for class templates, e.g.:</p>
<pre class="programlisting">
template&lt;typename T&gt; void func() {} int main() { func&lt;int&gt;(); func&lt;double&gt;(); }
</pre>
<p>The second alternative is for function template where one or
more of the template parameters are used in the function parameter
list. In this case, it is possible to omit those template
parameters from the template argument list, as if they had a
default value specified (<a href="#UsingTemplates">Using
Templates</a>). e.g.:</p>
<pre class="programlisting">
template&lt;typename T&gt; void func(T value) {} template&lt;typename T,typename U&gt; T func2(U value) { return T(value); } int main() { // T=int func(3); // T=double func(3.5); // T=int, U=double func2&lt;int&gt;(3.5); // T=std::vector&lt;std::string&gt;, U=int func2&lt;std::vector&lt;std::string&gt; &gt;(5); // specify both T and U // T=std::vector&lt;std::string&gt;, U=int func2&lt;std::vector&lt;std::string&gt;,int&gt;(5.7); }
</pre>
<p>This Template Argument Deduction can be used to make life easier
for the user of a function template, the same way that function
overloading makes life easier for the user of a normal function -
the correct function instantiation is automatically called based on
the function arguments provided.</p>
<p>In some circumstances, Template Argument Deduction will fail,
because there is an inconsistency caused during deduction - if two
parameters are declared to be the same type, and different types
are passed, then the compiler cannot deduce which to use. This
often occurs with <tt class=
"literal">std::max</tt>:std::max&lt;double&gt;(double,double)</p>
<pre class="programlisting">
int i=std::max(3,4.5);
</pre>
<p>The compiler cannot deduce whether to instantiate <tt class=
"literal">std::max&lt;int&gt;(int,int)</tt> or <tt class=
"literal">std::max&lt;double&gt;(double,double)</tt>, so it
generates an error. The solution is to provide an explicit template
argument list, or cast one of the arguments so it is the same type
as the other.</p>
<pre class="programlisting">
int i=std::max(static_cast&lt;double&gt;(3),4.5); // T=double int j=std::max&lt;int&gt;(3,4.5); // T=int
</pre>
<p>Note also that the return type is not considered when deducing
the template arguments in this way.</p>
<p>The Standard C++ Library contains a large number of templates,
which is partly what makes it so powerful - the Standard Library
code can be successfully used with classes that didn't exist when
the Standard was written.</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e369" id="d0e369"></a>Template
Requirements and Concepts</h2>
</div>
<p>Templates implicitly impose requirements on their parameters,
particularly <a href="#TemplateTypeParameters">Template Type
Parameters</a> and <a href="#TemplateTemplateParameters">Template
Template Parameters</a>. These requirements generally take the form
of operations that must work on objects of the appropriate type, or
class members that must exist and refer to objects or types or
functions (with the implicit extra requirement that the type
referred to is a class). A Concept is a set of requirements that
describe a useful feature of a type. For example, the C++ Standard
Library makes reference to things being Assignable or
Copy-Constructible; these are Concepts that make the following
requirements:</p>
<p>Given a type <tt class="literal">T</tt>, that type is
Copy-Constructible if the expression <tt class="literal">T
a(b);</tt> is defined, where <tt class="literal">b</tt> is an
expression of type <tt class="literal">T</tt>, and the resultant
object a has a value equivalent to the value of the expression
<tt class="literal">b</tt>.</p>
<p>That type is Assignable if the expression <tt class=
"literal">a=b;</tt> is defined, where <tt class="literal">a</tt>
and <tt class="literal">b</tt> are expressions of type <tt class=
"literal">T</tt>, and the value of the object referred to by the
expression a is equivalent to the value of the object referred to
by the expression <tt class="literal">b</tt> after the
assignment.</p>
<p>All built-in types are both Copy-Constructible and Assignable.
For classes, these requirements translate into requirements on
member functions:</p>
<p>A class <tt class="literal">T</tt> is Copy-Constructible if it
has a constructor which can be called with one argument of type
<tt class="literal">const-reference-to-T</tt>. This may be a
constructor with one argument, or it may be a constructor with more
than one argument, with default values provided for the remaining
arguments. The object thus constructed should have a value
equivalent to that of the argument<sup>[<a name="d0e424" href=
"#ftn.d0e424" id="d0e424">4</a>]</sup>.</p>
<p>A class <tt class="literal">T</tt> is Assignable if it defines a
copy-assignment operator (<tt class="literal">operator=()</tt>)
which has an argument of type <tt class="literal">T</tt>, or
<tt class="literal">const-reference-to-T</tt>. The object to which
the member function belongs should have a value equivalent to that
of the argument after the completion of such a member
function<sup>[<a name="d0e442" href="#ftn.d0e442" id=
"d0e442">5</a>]</sup>.</p>
<p>As a consequence, the <tt class="literal">std::auto_ptr</tt>
template does not fulfil these requirements, as it exhibits
transfer-of-ownership semantics on copy-construction and
assignment, and consequently the copy-constructor and
copy-assignment arguments are of type <tt class=
"literal">reference-to-T</tt> rather than <tt class=
"literal">const-reference-to-T</tt>. It is possible to write
Concept-checkers, templates which verify that a given type does
indeed fulfil all the syntactic requirements of a particular
Concept, even if the current template doesn't require all of them
in its current implementation. This also makes tracking down errors
easier - the compilation error generated by a failure in such a
Concept-Checker is more obviously a failure of the parameter type
to fulfil the concept requirements than a failure elsewhere in the
template definition.</p>
<p>It is possible that a class template may support different
operations, depending on which of several concepts a parameter type
fulfils the requirements for. This is made possible by a feature of
C++ class templates - member functions of class templates are only
instantiated if they are referenced. This means that a class
template can have a member function which only compiles if the
template parameters fulfil a particular concept, but the program
will compile even if they don't fulfil the concept, provided that
the function is not referenced for that set of parameters.
e.g.:</p>
<pre class="programlisting">
template&lt;typename T&gt; class MyClass { public: T* makeCopy(T* p) { return p-clone(); } }; MyClass&lt;int&gt; mci; double d; MyClass&lt;double&gt; mcd; double* pd=mcd.makeCopy(&amp;d); 
</pre>
<p><tt class="literal">mci</tt> is fine; as no reference is made to
the <tt class="literal">makeCopy</tt> member, it doesn't matter
that <tt class="literal">int</tt> isn't a class. However, the
reference to <tt class="literal">mcd.makeCopy</tt> causes an error,
as you cannot call member functions on a <tt class=
"literal">double</tt>.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e477" id="d0e477"></a>Template
Specialization and Overloading</h2>
</div>
<p>Template Specialization allows you to decide that for a specific
set of template parameters, the code instantiated for a template
should be different to the general case. Say, for example, you wish
to use a template with a new class as a <a href=
"#TemplateTypeParameters">Template Type Parameters</a>, and though
it has the same semantic behaviour as the classes the template was
designed for, the syntax is different, so the original template
won't compile with the new class as a parameter. The solution to
this problem is specialization.</p>
<p>Consider the following template function definition:</p>
<pre class="programlisting">
templatetypename T void func(T value) { value.add(3); }
</pre>
<p>This function assumes that the type substituted for the Template
Type Parameter <tt class="literal">T</tt> is a class with a member
function <tt class="literal">add</tt> that takes a single parameter
of a type that can be constructed from an <tt class=
"literal">int</tt>. Thus the following classes would be OK:</p>
<pre class="programlisting">
class T1 { public: void add(int i,double d=0.0); }; class T2 { public: std::string add(double d); };
</pre>
<p>However, the class <tt class="literal">T3</tt> below is not OK,
because <tt class="literal">Add</tt> is has a capital <tt class=
"literal">A</tt>.</p>
<pre class="programlisting">
class T3 { public: void Add(int i); };
</pre>
<p>This means that we cannot use our original function template
func for <tt class="literal">T3</tt>.</p>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e520" id="d0e520"></a>Explicit
Specialization</h2>
</div>
<p>What we can do, however, is Explicitly Specialize the template
for <tt class="literal">T3</tt>:</p>
<pre class="programlisting">
template&lt;&gt; void func&lt;T3&gt;(T3 value) { value.Add(3); }
</pre>
<p>There are two distinctive things about this declaration. The
first is the empty template parameter list after the <tt class=
"literal">template</tt> keyword, and the second is the presence of
the template argument list after the name of the function. This
tells the compiler that (a) a template is being specialized, and
(b) what set of template parameters apply for this specialization.
Then, whenever the compiler needs to instantiate the template with
this set of template parameters, it uses the specialization instead
of the general template.</p>
<p>Explicit Specialization applies both to class templates and
function templates. Here is an example for a class template, in
which the constructor for the general template accepts its
parameter by value, but the constructor for the <tt class=
"literal">std::string</tt> instantiation accepts its parameter by
<tt class="literal">const</tt>-reference, for efficiency:</p>
<pre class="programlisting">
template&lt;typename T&gt; class X { X(T x); }; template&lt;&gt; class X&lt;std::string&gt; { X(const std::string&amp; s); };
</pre>
<p>Explicit Specialization can be used with recursive class
templates to perform compile-time computations. e.g.:</p>
<pre class="programlisting">
template&lt;unsigned i&gt; struct Fibonacci { static const unsigned result=Fibonacci&lt;i-1&gt; ::result+Fibonaccii-2::result; }; template&lt;&gt; struct Fibonacci&lt;0&gt; { static const unsigned result=1; }; template struct Fibonacci&lt;1&gt; { static const unsigned result=1; }; int main() { std::cout&lt;&lt;Fibonacci&lt;5&gt;::result&lt;&lt;std::endl; }
</pre>
<p>The class template <tt class="literal">Fibonacci&lt;i&gt;</tt>
defines a constant <tt class="literal">result</tt> to be the i-th
number in the Fibonacci Sequence (1,1,2,3,5,8,13,. . . ) where
every element is the sum of the two previous ones. This can be seen
in the definition of the general template - the value of <tt class=
"literal">result</tt> is set to the sum of the <tt class=
"literal">result</tt>s of the previous two elements. However, by
itself, this is not enough, as each of those is the sum of the
previous two, and so on. We solve this by introducing the two
explicit specializations for <tt class=
"literal">Fibonacci&lt;0&gt;</tt> and <tt class=
"literal">Fibonacci&lt;1&gt;</tt>, to define the first two elements
in the series. This way the expansion of the template for any value
of <tt class="literal">i</tt> will eventually terminate, so the
sample main function will output <tt class="literal">8</tt>.</p>
<p>In addition to Explicit Specialization, there is <a href=
"#PartialSpecialization">Partial Specialization</a> for class
templates, and <a href="#FunctionTemplateOverloading">Function
Template Overloading</a> for function templates.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e583" id=
"d0e583"></a><span><a name="PartialSpecialization" id=
"PartialSpecialization"></a>Partial Specialization</span></h2>
</div>
<p>Partial Specialization allows you to specialize a class template
for a subset of the possible template parameters, where the
definition of the template should be the same for the whole subset,
but different to the general case. e.g.:</p>
<pre class="programlisting">
template&lt;typename T,typename U&gt; struct SameType { static const bool result=false; }; template&lt;typename T&gt; struct SameType&lt;T,T&gt; { static const bool result=true; }; int main() { std::cout &lt;&lt; &quot;Is int the same type as double?&quot; &lt;&lt;(SameType&lt;int,double&gt;::result ? &quot;Yes&quot; : &quot;No&quot;) &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Is std::string the same type &quot; &lt;&lt; &quot;as std::string?&quot; &lt;&lt;(SameType&lt;std::string, std::string&gt;::result ? &quot;Yes&quot; : &quot;No&quot;) &lt;&lt; std::endl; }
</pre>
<p>The partial specialization of the class template <tt class=
"literal">SameType</tt> looks a bit like a normal template
definition (the Template Parameter List is not empty), and a bit
like an explicit specialization (there is a Template Argument List
after the template name). The compiler knows it is a partial
specialization, because both these things are present. The partial
specialization applies to all instantations of the class template
where the full template argument list supplied for the general
definition can be written down in the form for the partial
specialization.</p>
<p>In this example, the partial template specialization applies if
both types are the same, so if the types are the same, the value of
<tt class="literal">result</tt> is <tt class="literal">true</tt>,
whereas if they are different, the general definition applies, and
the value of <tt class="literal">result</tt> is <tt class=
"literal">false</tt>. Therefore the example main function will
output:</p>
<div class="literallayout">
<p>Is int the same type as double?No Is std::string the same type
as std::string?Yes</p>
</div>
<p>Partial Specialization can be used for very fine control over
what template definition is used. For example, it is possible to
specialize on the <tt class="literal">const</tt>-ness of a template
type parameter, or for template type parameters which are
templates:</p>
<pre class="programlisting">
template&lt;typename T&gt; struct IsConst { static const bool result=false; }; template&lt;typename T&gt; struct IsConstconst T { static const bool result=true; }; template&lt;typename T&gt; struct IsVector { static const bool result=false; }; template&lt;typename T&gt; struct IsVector&lt;std::vector&lt;T&gt; &gt; { static const bool result=true; };
</pre>
<p>Thus the <tt class="literal">result</tt> member of <tt class=
"literal">IsConst</tt> is only true if the template parameter is a
<tt class="literal">const</tt> type, and the <tt class=
"literal">result</tt> member of <tt class="literal">IsVector</tt>
is only <tt class="literal">true</tt> if the template parameter is
an instantation of the <tt class="literal">std::vector</tt>
template.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e642" id=
"d0e642"></a><span><a name="FunctionTemplateOverloading" id=
"FunctionTemplateOverloading"></a>Function Template
Overloading</span></h2>
</div>
<p>You cannot partially specialize a function template, but
function templates can be overloaded, much the same as functions
can be overloaded. This means you can define multiple function
templates with the same name, but different template parameters, or
a different function signature. You can use this to much the same
effect as you can use partial specialization of class templates.
Consider the function template swap:</p>
<pre class="programlisting">
template&lt;typename T&gt; void swap(T&amp; lhs,T&amp; rhs) { T temp(lhs); lhs=rhs; rhs=temp; }
</pre>
<p>This is generally sufficient to swap two values of any type that
is copy-constructible, and assignable. However, it creates a new
object (<tt class="literal">temp</tt>), and copies data three
times. If this template is instantiated for a class that is
expensive to copy, then it could be very inefficient. To ease this,
we add a member function <tt class="literal">swap</tt> to our class
which swaps the value with that of another object as efficiently as
possible:</p>
<pre class="programlisting">
class ExpensiveToCopy { public: void swap(ExpensiveToCopy&amp; other); };
</pre>
<p>To call this, we now say <tt class="literal">a.swap(b)</tt>
rather than <tt class="literal">swap(a,b)</tt>, which is
inconsistent. We can solve this by specializing the function
template swap for <tt class="literal">ExpensiveToCopy</tt>:</p>
<pre class="programlisting">
template&lt;&gt; void swap&lt;ExpensiveToCopy&gt; (ExpensiveToCopy&amp; lhs, ExpensiveToCopy&amp; rhs) { lhs.swap(rhs); } 
</pre>
<p>All is well and good, but what if <tt class=
"literal">ExpensiveToCopy</tt> was a class template, such as
<tt class="literal">std::vector;</tt> we don't want to have to
specialize swap for every possible instantiation of the template.
The solution to this is Function Template Overloading - we just
write a new template function which overloads the first, e.g.:</p>
<pre class="programlisting">
template&lt;typename T&gt; void swap(std::vector&lt;T&gt;&amp; lhs,std::vector&lt;T&gt;&amp; rhs) { lhs.swap(rhs); }
</pre>
<p>The compiler chooses which overloaded template to instantiate
for each call using a mechanism called Partial Ordering in addition
to the normal overload resolution. This is quite complicated, but
essentially results in more specific overloads, like that of
<tt class="literal">swap</tt> for <tt class=
"literal">std::vector</tt> being preferred to the more general
equivalent, if the actual parameters are compatible with the more
specific one.</p>
<p>If Function Template Overloading does not suit your needs, and
you really do need Partial Specialization (4.2), the only option is
to write a helper class template, with a single static member
function that does all the work, and have your function template
forward to this function. You can then partially specialize the
helper class template to change the body of the static member.
e.g.:</p>
<pre class="programlisting">
template&lt;typename T&gt; class MyClass { public: void write(std::ostream&amp; os) const; }; template&lt;typename T&gt; struct PrintDataHelper { static void doPrint(T value) { std::cout &lt;&lt; &quot;The data is &quot; &lt;&lt; value &lt;&lt; std::endl; } }; template&lt;typename T&gt; struct PrintDataHelperMyClassT { static void doPrint(const MyClassT&amp; value) { std::cout &lt;&lt; &quot;The data is &quot;; value.write(std::cout); std::cout&lt;&lt;std::endl; } }; template&lt;typename T&gt; void printData(T value) { PrintDataHelper&lt;T&gt;::doPrint(value); }
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e695" id=
"d0e695"></a>Conclusion</h2>
</div>
<p>Hopefully, this article has given a glimpse into the power of
templates, and some insight into how they work and how they can be
utilised to make the task of writing and maintaining software
easier. They provide immense scope for writing generic and
customizable classes and functions, and form an essential C++
language feature, without which much of the Standard C++ Library
couldn't exist, or would be greatly restricted. Just about every
part of the library involves templates, from <tt class=
"literal">std::string</tt> (a typedef for <tt class=
"literal">std::basic_string&lt;char, std::char_traits&lt;char&gt;,
std::allocator&lt;char&gt; &gt;</tt>) to the I/O-streams classes
(e.g. <tt class="literal">std::ostream</tt> is a typedef for
<tt class="literal">std::basic_ostream&lt;char,
std::char_traits&lt;char&gt; &gt;</tt> ), to the containers and
algorithms that form the Standard Template Library portion, to the
classes that implement the Standard facets of the
localization/internationalization classes (e.g. <tt class=
"literal">std::ctype&lt;char&gt;</tt>).</p>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e145" href="#d0e145" id=
"ftn.d0e145">1</a>]</sup> If we were really writing a generic
function like this, we would probably pass the parameter as a const
reference, rather than as a value parameter to avoid copying large
objects - the same applies to <tt class="literal">void
printData(std::string value)</tt> above, it would be more usual to
write <tt class="literal">void printData(const std::string&amp;
value)</tt></p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e186" href="#d0e186" id=
"ftn.d0e186">2</a>]</sup> A compile-time constant is something that
can be evaluated at compile-time, such as an integer, or the
address of a global variable. There are restrictions on what can be
a compile-time constant, e.g. floating point values can not be
compile-time constants.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e249" href="#d0e249" id=
"ftn.d0e249">3</a>]</sup> If you wish to use std::vector or
std::list with a Template Type Parameter, then you have to take
account of the additional Allocator template parameter, even though
it is very rarely specified explicitly.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e424" href="#d0e424" id=
"ftn.d0e424">4</a>]</sup> If a class does not define any
copy-constructors (constructors which can be called with a single
argument of type reference-to-T or const-reference-to-T), then the
compiler will generate one automatically.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e442" href="#d0e442" id=
"ftn.d0e442">5</a>]</sup> If a class does not define any
copy-assignment operators which can be called with a single
argument of type T, reference-to-T or const-reference-to-T, then
the compiler will generate one automatically.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
