    <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  :: The C++ Template Argument Deduction</title>
        <link>https://members.accu.org/index.php/articles/409</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 #48 - Apr 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/c197/">48</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+197/">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;The C++ Template Argument Deduction</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 April 2002 17:46:09 +01:00 or Fri, 26 April 2002 17:46:09 +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>Introduction</h2>
</div>
<p>With the increasing popularity of the Standard C++ library and
the STL, it is becoming more and more important for a C++
programmer to understand the underlying mechanics of generic
programming in C++. In this article I will look into the little
known details of template argument deduction, an area of the C++
language that a lot of programmers find difficult to comprehend and
a knowledge of which is vital for using Standard C++
efficiently.</p>
<p>This article is intended for experienced C++ programmers who
wish to know the exact and yet clearly explained details of how
argument deduction is done in the C++ language. Deduction of
template arguments is an incredibly vast area and covering it in
detail and in all its entirety in one article would be impossible,
so I chose to pick out the most frequently used contexts that call
for template argument deduction and explain them in detail rather
than gloss over all cases of use of argument deduction. The
following uses of argument deduction are covered in this article:
&quot;Deducing template arguments from a function call expression&quot;,
&quot;Deducing template arguments when taking the address of a (member)
function template specialization&quot;, &quot;Deducing template arguments for
explicit specialization of a (member) function template&quot;.</p>
<p>Template argument deduction only pertains to function templates.
This means that whenever you reference a specialization of a class
template, you need to explicitly specify all template arguments. I
will therefore refer to function templates only in the remainder of
the article.</p>
<p>Although there are different cases when the language calls on
template argument deduction, they are all based on deducing
template arguments from a type. So it is here that the discussion
will start.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e29" id="d0e29"></a>Deducing
template arguments from a type</h2>
</div>
<p>Template parameters come in three flavors: 1) template template
parameters (associated with a class template, which I will denote
as <tt class="literal">TT</tt> for the remainder of the article),
2) type template parameters (associated with a type, denoted as
<tt class="literal">T</tt>), and 3) non-type template parameters
(most often associated with a constant value of integral or
enumeration type, denoted as <tt class="literal">i</tt>).</p>
<p>To deduce a template argument from a given type means that you
have two types - a <span class="emphasis"><em>type-id</em></span>
that contains one or more template parameters, I will call such a
<span class="emphasis"><em>type-id</em></span> <tt class=
"literal">P</tt> for the rest of the article (some combinations of
<tt class="literal">TT</tt>s, <tt class="literal">T</tt>s, and is
within one <tt class="literal">P</tt> are possible). For the moment
I will omit the details of how <tt class="literal">P</tt> is
obtained, suffice to say that in most cases it is one of the
function parameters of a function template declaration. The other
type that you have is a type-id that comprises no template
parameters, which I will call <tt class="literal">A</tt>, and an
attempt is made to find a class template for a <tt class=
"literal">TT</tt>, a type for <tt class="literal">T</tt>, and a
value for <tt class="literal">i</tt> so that <tt class=
"literal">P</tt> becomes identical to <tt class=
"literal">A</tt>.</p>
<p>Example:</p>
<pre class="programlisting">
template&lt;template&lt;class&gt; class TT, class T&gt;
T* alloc(TT&lt;T&gt;&amp; a) {
  return a.allocate(16);
}
</pre>
<p>For this template <tt class="literal">P</tt> can be <tt class=
"literal">TT&lt;T&gt;</tt>. If the type-id <tt class=
"literal">A</tt> from which we want to deduce <tt class=
"literal">TT</tt> and <tt class="literal">T</tt> is <tt class=
"classname">std::allocator&lt;int&gt;</tt>, then argument deduction
deduces <tt class="literal">TT</tt> to be <tt class=
"classname">std::allocator</tt> and <tt class="literal">T</tt> to
be <tt class="type">int</tt>. This results in <tt class=
"literal">P</tt> becoming <tt class=
"classname">std::allocator&lt;int&gt;</tt>, i.e. identical to
<tt class="literal">A</tt>.</p>
<p>So far so good, but what kind of type can <tt class=
"literal">A</tt> be and what combinations of <tt class=
"literal">TT</tt>s, <tt class="literal">T</tt>s, and is are allowed
in <tt class="literal">P</tt> so that template argument deduction
is possible on the template parameters that <tt class=
"literal">P</tt> consists of? The first part of the question</p>
<div class="informaltable">
<table border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>P's most specific type kind</th>
<th>Allowable form for P</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Object type</td>
<td><tt class="literal">cv-seq<sub>opt</sub> T</tt></td>
</tr>
<tr>
<td>Reference type</td>
<td><tt class="literal">T*</tt></td>
</tr>
<tr>
<td>Array type</td>
<td><tt class="literal">T&amp;</tt></td>
</tr>
<tr>
<td>Function type</td>
<td><tt class="literal">T[integral-constant-expression], type[i] ,
T[i]</tt></td>
</tr>
<tr>
<td>Pointer to data member type</td>
<td><tt class="literal">T type::*, type T::*, T T::*</tt></td>
</tr>
<tr>
<td>Pointer to member function type</td>
<td><tt class="literal">T type::*, type T::*, T T::*</tt></td>
</tr>
<tr>
<td>Class template specialization (class type)</td>
<td>
<div class="literallayout">
<p><tt class="literal">T(type::*)()cv-seq<sub>opt</sub>,<br>
T(type::*)(T)cv-seq<sub>opt</sub>,<br>
T(T::*)()cv-seq<sub>opt</sub>,<br>
T(T::*)(T)cv-seq<sub>opt</sub>,<br>
type(type::*)(T)cv-seq<sub>opt</sub>,<br>
type(T::*)()cv-seq<sub>opt</sub>,<br>
type(T::*)(T)cv-seq<sub>opt</sub></tt></p>
</div>
</td>
</tr>
<tr>
<td>Class template specialization (class type)</td>
<td><tt class="literal">class-template-name&lt;T&gt;,
class-template-name&lt;i&gt;, TT&lt;T&gt;, TT&lt;i&gt;,
TT&lt;&gt;</tt></td>
</tr>
&lt;/tbody&gt;
</table>
</div>
<p>is easier to answer since for template argument deduction the
language allows <tt class="literal">A</tt> to be any valid C++ type
(not a constant reference to constant function, of course). As for
<tt class="literal">P</tt>, only the following combinations are
allowed:</p>
<p>Where <tt class="literal">cv-seq</tt> designates any valid
sequence of <tt class="literal">const</tt> and <tt class=
"literal">volatile</tt> qualifiers, <sub>opt</sub> stands for
optional, <tt class="literal">(T)</tt> designates a list of
function parameters where at least one parameter is <tt class=
"literal">T</tt>, <tt class="literal">&lt;T&gt;</tt> designates a
list of template arguments where at least one template argument is
<tt class="literal">T</tt>, and, finally, <tt class=
"literal">&lt;i&gt;</tt> designates a list of template arguments
where at least one template argument is <tt class="literal">i</tt>.
type refers to any C++ type which consists of no template
parameters, i.e. it does not depend on the template parameters of
the function template. The construct class-template-name designates
a name of a class template that is not a template template
parameter. For instance this is shown in the following code
snippet, where <tt class="literal">P</tt> can be <tt class=
"classname">std::allocator&lt;T&gt;</tt> and class-template-name is
thus <tt class="classname">std::allocator</tt>.</p>
<pre class="programlisting">
template&lt;class T&gt;
T* alloc(std::allocator&lt;T&gt;&amp; a);
</pre>
<p>A few explanations are necessary to make sense of the above.
When there is more than one <tt class="literal">T</tt> in some of
the combinations shown, the <tt class="literal">T</tt>s do not need
to be the same type template parameter. A good example that
demonstrates this is the standard object generator for pointers to
member functions - the function template <tt class=
"literal">mem_fun_ref</tt>. Here is one of its declarations (the
name <tt class="literal">mem_fun_ref</tt> is overloaded):</p>
<pre class="programlisting">
template&lt;class R, class T, class A&gt;
mem_fun1_ref_t&lt;R,T,A&gt; mem_fun_ref(R(T::*)(A));
</pre>
<p>Here <tt class="literal">P</tt> can be <tt class=
"literal">R(T::*)(A)</tt>, which is a variant of <tt class=
"literal">T(T::*)(T)</tt>.</p>
<p>The second point that must be made about the allowable
combinations is that they can be applied recursively - any of the
24 forms shown can be used in place of <tt class="literal">T</tt>
in forming other permissible combinations, provided, of course,
that the resulting form is a legal C++ type-id. For instance
<tt class="literal">P</tt> having a form of <tt class=
"literal">type(T::*)(TT&lt;T&gt;,char)const</tt> is composed of
<tt class="literal">type(T::*)(T)const</tt> and <tt class=
"literal">TT&lt;T&gt;</tt> and is accepted by template argument
deduction (remember <tt class="literal">(T)</tt> designates a list
of function parameters where at least one parameter is <tt class=
"literal">T</tt>, so <tt class="literal">(TT&lt;T&gt;,char)</tt> is
a variation on <tt class="literal">(T)</tt>). The following
function template declaration clarifies this example further:</p>
<pre class="programlisting">
template&lt;template&lt;class&gt; class Alloc,
                     class C, class T&gt;
void dummy_alloc(
            void(C::*)(Alloc&lt;T&gt;,char)const);
</pre>
<p>Here one possible form of <tt class="literal">P</tt> is
<tt class="literal">void(C::*)(Alloc&lt;T&gt;)const</tt>. If the
corresponding <tt class="literal">A</tt> designates the type
<tt class=
"literal">void(Myclass::*)(std::allocator&lt;int&gt;)const</tt>,
then template argument deduction will deduce <tt class=
"literal">Alloc</tt> to be <tt class=
"classname">std::allocator</tt>, <tt class="literal">C</tt> to be
<tt class="literal">Myclass</tt>, and <tt class="literal">T</tt> to
be <tt class="type">int</tt>.</p>
<p>The forms involving template template parameters <tt class=
"literal">TT&lt;T&gt;</tt>, <tt class="literal">TT&lt;i&gt;</tt>,
<tt class="literal">TT&lt;&gt;</tt> require special elucidation.
Each of these forms specifies the use of a class template
<tt class="literal">TT</tt>, i.e. a class template specialization,
meaning that whenever you use any of the above three combinations
in <tt class="literal">P</tt>, you need to supply the same number
of template arguments as the declaration of <tt class=
"literal">TT</tt> specifies, unless the declaration of <tt class=
"literal">TT</tt> contains one or more <span class=
"emphasis"><em>default template arguments</em></span> in which case
the trailing template arguments can be omitted. Note that the angle
brackets must be present even if all <tt class="literal">TT</tt>'s
template parameters have defaults. The following example
demonstrates the use of a template template parameter in <tt class=
"literal">P</tt> where <tt class="literal">TT</tt> has default
template arguments for all its parameters.</p>
<pre class="programlisting">
template&lt;class T, template&lt;class=T&gt; class TT&gt; &gt;
void foo(int(*arr)(TT&lt;&gt;));
</pre>
<p>In this example <tt class="literal">P</tt> can be <tt class=
"literal">int(*arr)(TT&lt;T&gt;)</tt> and given <tt class=
"literal">A</tt> of <tt class=
"literal">int(*)(std::allocator&lt;int&gt;)</tt> template argument
deduction will resolve <tt class="literal">T</tt> to <tt class=
"type">int</tt> and <tt class="literal">TT</tt> to <tt class=
"classname">std::allocator</tt>.</p>
<p>Although there is a form <tt class="literal">TT&lt;&gt;</tt>
among the allowable choices for <tt class="literal">P</tt>, it
shouldn't be taken as a template template parameter with no
template arguments. In fact it just means that the list of
arguments doesn't contain any other template parameters and must
contain non-dependent types, which is illustrated by the following
example:</p>
<pre class="programlisting">
template&lt;template&lt;class, class&gt; class Sequence&gt;
void empty_sequence(Sequence&lt;int,
          std::allocator&lt;int&gt; &gt;&amp; seq) {
  seq.empty();
}
</pre>
<p>In this function template, <tt class="literal">P</tt> can be
<tt class="classname">Sequence&lt;T, Alloc&lt;T&gt; &gt;</tt>,
which is a variant of <tt class="literal">TT&lt;T1,T2&gt;</tt> (it
is allowed to treat the form <tt class="literal">TT&lt;T&gt;</tt>
as <tt class="literal">TT&lt;T1,T2&gt;</tt> where <tt class=
"literal">T1</tt> and <tt class="literal">T2</tt> are type template
parameters with <tt class="literal">T2</tt> being <tt class=
"literal">TT&lt;T&gt;</tt>, see the notes to the table of allowable
forms) where, as you can see, the type parameter <tt class=
"literal">T1</tt> is <tt class="literal">T</tt> and <tt class=
"literal">T2</tt> is <tt class="classname">Alloc&lt;T&gt;</tt>.
Given a corresponding <tt class="literal">A</tt> of <tt class=
"classname">std::vector&lt;int, std::allocator&lt;int&gt;
&gt;</tt>, template argument deduction will be able to deduce
<tt class="classname">Sequence</tt> to be <tt class=
"classname">std::vector</tt>, <tt class="classname">Alloc</tt> to
be <tt class="classname">std::allocator</tt>, and <tt class=
"literal">T</tt> to be int in spite of the <tt class=
"literal">T</tt> appearing twice within the <tt class=
"literal">P</tt>. In fact it will deduce <tt class="literal">T</tt>
twice and, with above <tt class="literal">A</tt>, each time to the
same type.</p>
<p>But what happens if <tt class="literal">P</tt> references a type
template parameter <tt class="literal">T</tt> more than once and
the corresponding A supplies two different types for each
occurrence of <tt class="literal">T</tt> in <tt class=
"literal">P</tt>? For instance, in the previous example if
<tt class="literal">A</tt> had a form of <tt class=
"classname">std::vector&lt;int,std::allocator&lt;char&gt;
&gt;</tt>, then template argument deduction would deduce <tt class=
"literal">T</tt> to have type <tt class="type">int</tt> in one
place and <tt class="type">char</tt> in the other. The language
prohibits these scenarios and deduction fails for <tt class=
"literal">P</tt>'s function template when the context supplies such
an <tt class="literal">A</tt>.</p>
<p>A careful look at the table of allowable forms reveals that it's
not possible to form a <span class=
"emphasis"><em>qualified</em></span> <tt class="literal">P</tt> by
using them (even if the use is recursive). This means that if you
make <tt class="literal">P</tt> qualified, template argument
deduction is not possible for it. For example:</p>
<pre class="programlisting">
template&lt;template&lt;class, class&gt; class Sequence,
  template&lt;class&gt; class Alloc, class T&gt;
void empty_sequence(T::Sequence&lt;T, Alloc&lt;T&gt; &gt;&amp;);
</pre>
<p>In this code sample one possible <tt class="literal">P</tt> is
<tt class="classname">T::Sequence&lt;T,Alloc&lt;T&gt; &gt;</tt> and
because of this <tt class="literal">P</tt> being qualified,
template argument deduction is not possible regardless of the form
that the corresponding <tt class="literal">A</tt> has.</p>
<p>As I said before, in forming <tt class="literal">P</tt> a
standard conforming compiler is allowed to replace <tt class=
"literal">T</tt> in any of the allowable forms with another form
from the table, but no such provision is made for <tt class=
"literal">i</tt>. There are only four forms that contain <tt class=
"literal">i</tt> in the table, these are <tt class=
"literal">type[i]</tt>, <tt class="literal">T[i]</tt>, <tt class=
"literal">class-template-name&lt;i&gt;</tt>, and <tt class=
"literal">TT&lt;i&gt;</tt>. And in all these forms <tt class=
"literal">i</tt> is used as an expression that has the form of a
simple identifier. Thus, by strictly following the rules it is not
possible to get such <tt class="literal">P</tt> that would contain
<tt class="literal">i</tt> in a form different from a simple
identifier. It follows that if you have a <tt class=
"literal">P</tt> wherein <tt class="literal">i</tt> is used in an
expression which doesn't have the form of a simple identifier,
template argument deduction is not possible.</p>
<pre class="programlisting">
template&lt;unsigned i&gt;
void foo(int(&amp;p)[+i]);
</pre>
<p>In this example <tt class="literal">P</tt> can be <tt class=
"literal">int[+i]</tt>. And no matter what form the corresponding
<tt class="literal">A</tt> has, no argument deduction is possible
for this <tt class="literal">P</tt>.</p>
<p>In a similar manner, no recursive use of the allowable forms
enables to get <tt class="literal">P</tt> of, for example, this
form: <tt class="literal">type(*)[sizeof(T)]</tt>. This is
illustrated in the following code snippet:</p>
<pre class="programlisting">
template&lt;class T, template&lt;class&gt; class TT&gt;
void foo(int(*arr)[sizeof(TT&lt;T&gt;)]);
</pre>
<p>Which again means that should argument deduction be presented
with such <tt class="literal">P</tt>, it will not deduce any
template parameters in it.</p>
<p>In general, a <tt class="literal">P</tt> which is qualified or
contains <tt class="literal">i</tt> involved in an expression other
than a simple identifier (that is, not used by itself) or contains
any other template parameter used in an expression such as
<tt class="literal">sizeof</tt> is conventionally called a
<span class="emphasis"><em>nondeduced context</em></span>. Having
such a <tt class="literal">P</tt> in a template declaration is not
ill-formed, it's just that template argument deduction cannot
deduce any template parameters in that <tt class="literal">P</tt>
regardless of the form of the corresponding <tt class=
"literal">A</tt>. This effectively means that the template
parameters that such <tt class="literal">P</tt> comprises must be
either explicitly specified or deduced elsewhere. I'd like to note
here that it is not possible to get a nondeduced context by
recursively applying only the allowable forms. When consulting the
table of allowable forms you should regard a nondeduced conext as a
non-dependent type, which is denoted there as type.</p>
<p>Now that I've explained the concept of deducing template
arguments from a type, it is high time that I embark upon some of
the contexts that call on template argument deduction.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e677" id="d0e677"></a>Deducing
template arguments when taking the address of a (member) function
template specialization</h2>
</div>
<p>It is not uncommon for C++ programmers to initialize an object
of type pointer to (member) function with an expression referring
to a (member) function. As is the case with non-template (member)
functions, (member) function template specializations can be used
in such contexts too, much like normal non-template functions:</p>
<pre class="programlisting">
ptrdiff_t count_chr(const char* str,
                    const char ch) {
  // using the specialization of the standard
  // 'count' algorithm
  ptrdiff_t (* pf)(const char*, const char*,
      const char&amp;)
    = std::count&lt;const char*, char&gt;;
 return (*pf)(str, str+std::strlen(str), ch);
}
</pre>
<p>One thing to remember here is that there are no implicit
conversions etween pointers to functions of different types and
pointers to member functions of the same class of different types.
There must be an exact match:</p>
<pre class="programlisting">
struct test {
  void update1(char*, char*);
  void update2(const char*, const char*);
  void update3(const char*, const char*,
                        int=0);
};
void  testing() {
  // Error, no exact match
  void (test::* pmf1)(const char*,
        const char*) = &amp;test::update1;
  // OK
  void (test::* pmf2)(const char*,
        const char*) = &amp;test::update2;
  // Error, default arguments are not
  // part of function type
  void (test::* pmf3)(const char*,
        const char*) = &amp;test::update3;
}
</pre>
<p>Before plunging right into the nitty-gritty details of argument
deduction, it would be helpful if I clarified the meaning of the
term <span class="emphasis"><em>function template
specialization</em></span>, which has already been used a number of
times in this article (member function template specializations
follow the same conventions and will be omitted from the following
discussion).</p>
<p>A function template specialization is a use of a function
template name with a full set of template arguments that uniquely
identifies exactly one specialization. For instance in the code
example above <tt class="classname">std::count&lt;const
char*,char&gt;</tt> is a specialization of the function template
<tt class="classname">count</tt>. Sometimes a set of template
arguments is given explicitly in a specialization and the number of
arguments in the set matches the number of template parameters of
the corresponding template, sometimes the set contains fewer
template arguments than the number of template parameters of the
matching function template, and sometimes it contains no template
arguments at all (even the angle brackets could be left out).
Whenever some or all template arguments are omitted, they must be
deducible from the context and the result of the deduction is a
function template specialization. When a full set of template
arguments is specified, no template argument deduction takes
place.</p>
<p>The point is that a C++ programmer never deals with function
templates themselves (except, for example, when they declare,
define or explicitly specialize them). Most of the time it is a
specialization of a given template that a programmer uses. Below an
earlier code fragment has been modified to clarify the points that
were made earlier:</p>
<pre class="programlisting">
ptrdiff_t count_chr(const char* str,
                    const char ch) {
  // Using the specialization of the standard
  //    'count' algorithm without specifying
  //    template arguments explicitly.
  // 1. Name lookup finds the function template
  //  template&lt;class InIter, class T&gt;
  //  typename 
  //    iterator_traits&lt;InIter&gt;::difference_type
  //      count(InIter first, InIter last,
  //                    const T&amp; val);
  // 2. Template argument deduction deduces the
  //  template arguments to have types 'const
  //  char*' and 'char' respectively. Thus
  //  making the expression 'std::count'
  //  equivalent to 'std::count&lt;const char*,
  //  char&gt;'
  //
   ptrdiff_t (* pf)(const char*,
       const char*, const char&amp;) = std::count;
   return (*pf)(str, str+std::strlen(str), ch);
}
</pre>
<p>Returning to template argument deduction when taking the address
of a (member) function template, what I need to explain is how
<tt class="literal">P</tt>'s and <tt class="literal">A</tt>'s are
formed when some template arguments are not specified. The answer
is surprisingly simple - there is just one <tt class=
"literal">P</tt> and one <tt class="literal">A</tt>. <tt class=
"literal">P</tt> is the type of the initializer expression
(possibly converted to a type of pointer to function) and
<tt class="literal">A</tt> is the type of the object being
initialized.</p>
<p>For instance in the code sample above:</p>
<pre class="programlisting">
P is typename iterator_traits&lt;InIter&gt;::
difference_type(*)(InIter, InIter, const T&amp;),
</pre>
<p>which in terms of the conventions used in the table of allowable
forms is a variant of <tt class="literal">type(*)(T)</tt>.</p>
<p><tt class="literal">A</tt> is <tt class=
"literal">ptrdiff_t(*)(const char*, const char*, const
char&amp;)</tt> and template argument deduction will be seeking
such types for <tt class="type">InIter</tt> and <tt class=
"literal">T</tt> that will make <tt class="literal">P</tt>
identical to <tt class="literal">A</tt>.</p>
<p>If the initializer expression was <tt class=
"classname">std::count&lt;const char*&gt;</tt>, only one template
argument would have to be deduced (since one is specified
explicitly), i.e. in that case <tt class="literal">P</tt> would
be:</p>
<pre class="programlisting">
typename iterator_traits&lt;const char*&gt;::
                     difference_type(*)(
   const char*, const char*, const T&amp;)
</pre>
<p>It is easy enough to write the initializer in such a way that no
matching specialization could be found. For example the initializer
of the form <tt class="classname">std::count&lt;char*&gt;</tt> will
result in <tt class="literal">P</tt> being:</p>
<pre class="programlisting">
typename iterator_traits&lt;char*&gt;::
   difference_type(*)(char*, char*, const T&amp;),
</pre>
<p>which doesn't enable template argument deduction to make such
<tt class="literal">P</tt> identical to the corresponding
<tt class="literal">A</tt>.</p>
<p>If the name of the function template whose address is being
taken is overloaded, then there are as many <tt class=
"literal">P</tt>s as there are overloaded function templates by
that name and template argument deduction will be performed against
all of them with the same A. Those templates for which deduction
does not succeed will not be considered further. If the initializer
expression does not contain the angle brackets, non-template
functions will also be considered, i.e. if the namespace std
contained a function declaration:</p>
<pre class="programlisting">
ptrdiff_t count(const char*,
                const char*, const char&amp;);
</pre>
<p>this function would also be considered in the example above. It
is then up to overload resolution to decide which function template
specialization is the most specialized and choose it. Note that a
non-template function is always preferred to any function template
specialization, as a non-template function is considered more
specialized than a corresponding function template
specialization.</p>
<p>It is quite common for <tt class="literal">P</tt> to contain
multiple references to the same template parameter and my example
with the standard <tt class="classname">count</tt> algorithm showed
it. The first reference was in the return type
iterator_traits&lt;InIter&gt;::difference_type, which is a
nondeduced context and is therefore ignored, meaning that
<tt class="type">InIter</tt> must be deducible from its other
occurrences in the <tt class="literal">P</tt>. The second and the
third appearances are the same and have the form InIter. As the
corresponding parts of <tt class="literal">A</tt> also constitute
the same type <tt class="type">const char*</tt>, <tt class=
"type">InIter</tt> can be deduced from either part to be the same
type. If they were different, for instance, if <tt class=
"literal">A</tt> was <tt class="literal">ptrdiff_t(*)(const char*,
char*, const char&amp;)</tt>, then <tt class="type">InIter</tt>
would be deduced to be <tt class="type">const char*</tt> in one
part and to <tt class="type">char*</tt> in the other. Whenever such
a situation arises, argument deduction fails. See the discussion on
this issue in the previous chapter.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e828" id="d0e828"></a>Deducing
template arguments for explicit specialization of a (member)
function template</h2>
</div>
<p>Consider the following piece of code in which two overloaded
declarations of the function template <tt class="literal">foo</tt>
are defined:</p>
<pre class="programlisting">
template&lt;class T&gt;
struct example {
  template&lt;class U&gt; // 1st member template
  int foo(U);
  template&lt;class U&gt; // 2nd member template
  int foo(U*);
};
</pre>
<p>Now suppose I have an explicit specialization of the following
form in the same translation unit:</p>
<pre class="programlisting">
template&lt;&gt; template&lt;&gt;
int example&lt;char&gt;::foo(int*);
</pre>
<p>But which member function template is explicitly specialized
here? One possible answer is that it is the second one, but is it
really? The truth is that for explicit specializations of (member)
function templates, template argument deduction is done in a way
similar to that I covered in the previous chapter - <tt class=
"literal">A</tt> is the function type of an explicit specialization
named <tt class="literal">N</tt> and <tt class="literal">P</tt>'s
are the function types of templates with name <tt class=
"literal">N</tt> that are members of the same scope as the explicit
specialization. Template argument deduction then makes an attempt
to make each of the <tt class="literal">P</tt>'s identical to
<tt class="literal">A</tt> (for more on that see the chapter
&quot;Deducing template arguments from a type&quot; at the beginning of this
article). Those templates for which argument deduction fails are
not considered further. Those for which it does are submitted to
overload resolution and the latter makes a decision as to which of
the templates is more specialized than the others. When it can make
this decision, the explicit specialization is considered to
specialize the most specialized template, otherwise the explicit
specialization declaration is ill-formed.</p>
<p>In the example shown <tt class="literal">A</tt> is <tt class=
"literal">int example&lt;char&gt;::foo(int*)</tt>. Given that the
explicit specialization is a member of the class scope <tt class=
"literal">example&lt;char&gt;</tt>, there are two <tt class=
"literal">P</tt>'s: <tt class="literal">P<sub>1</sub></tt> is
<tt class="literal">int example&lt;char&gt;::foo(U)</tt>, and
<tt class="literal">P<sub>2</sub></tt> is <tt class="literal">int
example&lt;char&gt;::foo(U*)</tt>. For <tt class=
"literal">P<sub>1</sub></tt> argument deduction succeeds with
<tt class="literal">U</tt> deduced to be <tt class=
"type">int*</tt>. For <tt class="literal">P<sub>2</sub></tt> it
succeeds too resulting in <tt class="literal">U</tt> having type
<tt class="type">int</tt>. So both member function templates are
submitted to overload resolution for finding out which of them is
more specialized than the other, and the latter selects the second,
meaning that the explicit specialization specializes the second
member template.</p>
<p>When declaring an explicit specialization, it is possible to
explicitly specify some or all the template arguments of the
function template being specialized. The arguments will actually be
applied to the templates of the same name and scope as the explicit
specialization. This can come handy in influencing the result of
argument deduction. For example if the same translation unit
contains another explicit specialization of the form:</p>
<pre class="programlisting">
template&lt;&gt; template&lt;&gt;
int example&lt;char&gt;::foo&lt;int*&gt;(int*);
</pre>
<p>Things will proceed as follows:</p>
<div class="literallayout">
<p><tt class="literal">A</tt> is <tt class="literal">int
example&lt;char&gt;::foo(int*)</tt>,<br>
<tt class="literal">P<sub>1</sub></tt> is <tt class="literal">int
example&lt;char&gt;::foo(int*)</tt>,<br>
and <tt class="literal">P<sub>2</sub></tt> is <tt class=
"literal">int example&lt;char&gt;::foo(int**)</tt>.</p>
</div>
<p>No argument deduction will take place at all since the two
member templates have just one template parameter and it has been
specified. Since <tt class="literal">P<sub>2</sub></tt> now has a
different type from the type of the explicit specialization it is
no longer considered, thus the explicit specialization specializes
the first member template.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e950" id="d0e950"></a>Deducing
template arguments from a function call expression</h2>
</div>
<p>When name lookup finds a name in a function call expression to
denote a function template or a (non-special) member function
template and the call leaves one or more trailing template
arguments unspecified or has a form without the angle brackets,
template argument deduction comes into action:</p>
<pre class="programlisting">
int main() {
  int data[] = {3, 0, -1, -3, 16, };

  // Name lookup finds the function template
  // template&lt;class RandomAccessIterator&gt;
  // void sort(RandomAccessIterator first,
  //           RandomAccessIterator last);
  //
  // Template argument deduction deduces the
  // template argument to have type 'int*'.
  // This results in a call to the function
  // template specialization
  // 'void sort&lt;int*&gt;(int* first, int* last)'.

  std::sort(data,
            data + sizeof data/sizeof*data);

  std::vector&lt;int, std::allocator&lt;int&gt; &gt;
       container, empty;

  // Name lookup finds the member function
  // template
  // template&lt;class InputIterator&gt;
  // void vector&lt;int,allocator&lt;int&gt; &gt;::assign(
  //   InputIterator first, InputIterator last);
  //
  // Template argument deduction deduces the
  // template argument to have type 'int*'.
  // This results in a call to the function
  // template specialization
  // 'void vector&lt;int,allocator&lt;int&gt; &gt;::
  //               assign&lt;int*&gt;(int*, int*)'.

  container.assign(data,
             data + sizeof data/sizeof*data);

  // Argument dependent name lookup finds the
  // namespace scope function template
  // template&lt;class T, class Alloc&gt;
  // bool operator!=(const vector&lt;T,Alloc&gt;&amp;,
  //                 const vector&lt;T,Alloc&gt;&amp;);
  //
  // Template argument deduction deduces T to
  // be 'int' and Alloc to be std::allocator.

  if(container != empty)  container.clear();
}
</pre>
<p>Unlike the contexts requiring template argument deduction that I
looked at before, which were all more alike than different in terms
of how <tt class="literal">P</tt>'s and <tt class=
"literal">A</tt>'s were formed, this case is really distinctive and
you will see why shortly. It is also the most frequently used form
of template argument deduction, so I will back its description up
with more case studies.</p>
<p>The distinction from what I showed earlier is that when
deduction starts for a (member) function template: 1) there can be
more than one <tt class="literal">P</tt>, 2) the number of
<tt class="literal">A</tt>'s is always the same as the number of
<tt class="literal">P</tt>'s. In fact, any function parameter which
depends on a template parameter that has not been explicitly
specified (see the earlier discussion on function templates and
function template specializations) constitutes a <tt class=
"literal">P</tt>. If all template arguments are explicitly
specified, there are no <tt class="literal">P</tt>'s and no
argument deduction takes place. If the i-th function parameter of a
function template qualifies as <tt class="literal">P</tt> (I will
call it <tt class="literal">P<sub>i</sub></tt> for the rest of the
article), then the <tt class="literal">i</tt>-th argument of the
corresponding function call expression is <tt class=
"literal">A</tt> (which I will call <tt class=
"literal">A<sub>i</sub></tt>).</p>
<p>Different to the cases I covered before, here every <tt class=
"literal">P<sub>i</sub></tt> and <tt class=
"literal">A<sub>i</sub></tt> can undergo a transformation before
template argument deduction takes place. Below are the details of
how this process goes:</p>
<p>First every <tt class="literal">A<sub>i</sub></tt> is studied
and:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>if <tt class="literal">A<sub>i</sub></tt> is a reference type,
it is converted to the underlying type of the reference and is
considered an lvalue<sup>[<a name="d0e1029" href="#ftn.d0e1029" id=
"d0e1029">1</a>]</sup>;</p>
</li>
<li>
<p>if <tt class="literal">A<sub>i</sub></tt> is an lvalue of array
type and <tt class="literal">A<sub>i</sub></tt> is not a reference
type, the array-to-pointer conversion is applied to <tt class=
"literal">A<sub>i</sub></tt>;</p>
</li>
<li>
<p>if <tt class="literal">A<sub>i</sub></tt> is an lvalue of
function type and <tt class="literal">A<sub>i</sub></tt> is not a
reference type, the function-to-pointer conversion is applied to
<tt class="literal">A<sub>i</sub></tt>;</p>
</li>
<li>
<p>if <tt class="literal">A<sub>i</sub></tt> is not a reference
type, top-level const and volatile qualifiers are removed from
<tt class="literal">A<sub>i</sub></tt>.</p>
</li>
</ul>
</div>
<p>After that is done, every <tt class="literal">P<sub>i</sub></tt>
is examined and:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>top-level const and volatile qualifiers (if any) are removed
from <tt class="literal">P<sub>i</sub></tt>;</p>
</li>
<li>
<p>if <tt class="literal">P<sub>i</sub></tt> is a reference type,
the underlying type of <tt class="literal">P<sub>i</sub></tt> is
substituted for it.</p>
</li>
</ul>
</div>
<p>For the rest of this section, whenever I mention <tt class=
"literal">P<sub>i</sub></tt> or <tt class=
"literal">A<sub>i</sub></tt>, I'll be referring to their
transformed versions.</p>
<p>With the information from the previous paragraphs in mind and
the example I presented at the beginning of this section, I can now
show how <tt class="literal">P</tt>'s and <tt class=
"literal">A</tt>'s are formed for the expression <tt class=
"literal">container != empty</tt>, for which name lookup finds the
function template <tt class="literal">operator!=(const
vector&lt;T,Alloc&gt;&amp;, const vector&lt;T,Alloc&gt;&amp;)</tt>
as a possible candidate. This template has two function parameters,
which depend on the template parameters. Both the function
parameters are of reference type and are the same and hence the
underlying type of the references is used in determining <tt class=
"literal">P</tt>'s - <tt class="literal">P<sub>1</sub></tt>,
<tt class="literal">P<sub>2</sub></tt> are <tt class=
"literal">const vector&lt;T, Alloc&gt;</tt>. The corresponding
<tt class="literal">A</tt>'s are also the same - <tt class=
"literal">A<sub>1</sub></tt>, <tt class=
"literal">A<sub>2</sub></tt> are <tt class=
"literal">std::vector&lt;int, std::allocator&lt;int&gt; &gt;</tt>.
Template argument deduction then deduces <tt class="literal">T</tt>
to be <tt class="type">int</tt> and <tt class="literal">Alloc</tt>
to be <tt class="classname">std::allocator</tt>, which results in a
call to the function template specialization</p>
<pre class="programlisting">
bool operator!=&lt;int,std::allocator&gt;(
          const vector&lt;int,std::allocator&gt;&amp;,
          const vector&lt;int,std::allocator&gt;&amp;)
</pre>
<p>The fact that argument deduction makes each <tt class=
"literal">P<sub>i</sub></tt> identical to the corresponding
<tt class="literal">A<sub>i</sub></tt> has a major implication on
calling (member) function templates, for it leaves no room for
user-defined conversions on <tt class="literal">A</tt>'s. Here is
an example:</p>
<pre class="programlisting">
#include &lt;algorithm&gt;
#include &lt;functional&gt;
#include &lt;iostream&gt;

struct example {
  static void foo(int i) {
    std::cout &lt;&lt; i &lt;&lt; '\n';
  }
  typedef void  fun_t(int);
  operator  fun_t*() const {
    return  foo;
  }
};

int main() {
  int data[] = {3, 0, -1, -3, 16};
  example inst;

  // std::for_each(data,
  //          data + sizeof data/sizeof*data,
  //          std::ptr_fun(inst));
  std::for_each(data,
              data + sizeof data/sizeof*data,
              example::foo);
}
</pre>
<p>Let's look at the lines that were commented out and the function
call expression <tt class="literal">std::ptr_fun(inst)</tt> in
particular. What happens there is that name lookup finds the
following two function templates in the scope of the namespace
<tt class="literal">std</tt>:</p>
<pre class="programlisting">
template&lt;class Arg, class Res&gt;
pointer_to_unary_function&lt;Arg,Res&gt;
                    ptr_fun(Res(*)(Arg);

template&lt;class Arg1, class Arg2, class Res&gt;
pointer_to_binary_function&lt;Arg1,Arg2,Res&gt;
                    ptr_fun(Res(*)(Arg1,Arg2);
</pre>
<p>For the first function template there is one <tt class=
"literal">P</tt> and one <tt class="literal">A</tt>. <tt class=
"literal">P<sub>1</sub></tt> is <tt class=
"literal">Res(*)(Arg)</tt>, which, in terms of the conventions used
in the table of allowable forms, is a variant of <tt class=
"literal">T(*)(T)</tt>. The corresponding <tt class=
"literal">A<sub>1</sub></tt> is the type <tt class=
"literal">example</tt>. It is obvious enough that there exist no
such types for the template parameters <tt class="literal">Res</tt>
and <tt class="literal">Arg</tt> that would make <tt class=
"literal">P<sub>1</sub></tt> identical to <tt class=
"literal">A<sub>1</sub></tt>. There is, however, a user-defined
conversion from an expression of type example to type <tt class=
"literal">void(*)(int)</tt>. If it was selected (like in the case
of nontemplate functions), argument deduction would deduce
<tt class="literal">Res</tt> to be <tt class="type">void</tt> type
and <tt class="literal">Arg</tt> to be <tt class="type">int</tt>.
But, as I said before, the language prohibits this and argument
deduction fails. Quite similarly, template argument deduction fails
for the second function template. This all leaves the set of
candidates submitted to overload resolution empty, thus making the
construct <tt class="literal">std::ptr_fun(inst)</tt> ill-formed in
the context shown above.</p>
<p>Since you can always perform user-defined conversions inside the
body of a function template, the restriction of precluding
userdefined conversions on <tt class="literal">A</tt>'s can be
easily circumvented. And a nice example of that can, not
surprisingly, be found in the Standard C++ library. Let's take a
look at the function object generator <tt class=
"classname">bind2nd</tt>, here is its possible implementation:</p>
<pre class="programlisting">
template&lt;class BinOp, class T&gt;
binder2nd&lt;BinOp&gt; bind2nd(const BinOp&amp; op,
                         const T&amp; second) {
  return binder2nd&lt;BinOp&gt;(op, typename
         BinOp::second_argument_type(second));
}
</pre>
<p>When called, this function template deduces <tt class=
"literal">T</tt> to be whatever type the second function argument
has (except that it will effectively strip the type of the second
argument of the possible const qualifier) and then explicitly
converts it to the type required. Here is a small program that
shows how this works:</p>
<pre class="programlisting">
#include &lt;algorithm&gt;
#include &lt;functional&gt;
#include &lt;iostream&gt;
#include &lt;iterator&gt;

struct  example {
  operator int() const {
    return 3;
  }
};

int main() {
  int data[] = {3, 0, -1, -3, 16};
  example inst;
  std::transform(data,
   data + sizeof data/sizeof*data,
   std::ostream_iterator&lt;int&gt;(std::cout, &quot;  &quot;),
   std::bind2nd(std::modulus&lt;int&gt;(), inst));
}
</pre>
<p>There's also another way in which argument deduction from a
function call expression differs from the cases I looked at in the
previous sections. It differs in that it allows each <tt class=
"literal">P<sub>i</sub></tt> to be not identical to the
corresponding <tt class="literal">A<sub>i</sub></tt> . The
following is allowed:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><tt class="literal">P<sub>i</sub></tt> can be more
const/volatile qualified than <tt class=
"literal">A<sub>i</sub></tt>;</p>
</li>
<li>
<p>if <tt class="literal">P<sub>i</sub></tt> is a pointer or
pointer to member type, it can be a type to which an expression of
type <tt class="literal">A<sub>i</sub></tt> can be converted via a
qualification conversion;</p>
</li>
<li>
<p>if <tt class="literal">P<sub>i</sub></tt> has one of the
following forms: <tt class=
"literal">class-templatename&lt;T&gt;</tt>, <tt class=
"literal">class-template-name&lt;i&gt;</tt>, <tt class=
"literal">cv-seq<sub>opt</sub> class-template-name&lt;T&gt;*</tt>,
or <tt class="literal">cv-seqopt classtemplate-name&lt;i&gt;*</tt>
it can be a type derived from <tt class=
"literal">A<sub>i</sub></tt>.</p>
</li>
</ul>
</div>
<p>Of course, providing that it is possible to find such types for
the template parameters of <tt class="literal">P<sub>i</sub></tt>
that <tt class="literal">P<sub>i</sub></tt> becomes identical to
its <tt class="literal">A<sub>i</sub></tt>, these three
alternatives are not considered.</p>
<p>The example of the use of the function template <tt class=
"classname">bind2nd</tt> that I just presented also demonstrates
the case where <tt class="literal">P</tt>'s are different from its
corresponding <tt class="literal">A</tt>'s. Indeed, in the function
call expression <tt class=
"literal">std::bind2nd(std::modulus&lt;int&gt;(),inst)</tt>
<tt class="literal">A<sub>1</sub></tt> is the type <tt class=
"literal">std::modulus&lt;int&gt;</tt> and <tt class=
"literal">A<sub>2</sub></tt> is the type example. The corresponding
<tt class="literal">P</tt>'s are: <tt class=
"literal">P<sub>1</sub></tt> is <tt class="literal">const
BinOp</tt>, <tt class="literal">P<sub>2</sub></tt> is <tt class=
"literal">const T</tt>. And template argument deduction deduces
<tt class="literal">BinOp</tt> to be <tt class=
"classname">std::modulus&lt;int&gt;</tt> and <tt class=
"literal">T</tt> to be example, which results in a call to the
function template specialization:</p>
<pre class="programlisting">
binder2nd&lt;std::modulus&lt;int&gt; &gt;
      bind2nd(const std::modulus&lt;int&gt;&amp;,
              const example&amp;)
</pre>
<p>Given the way the deduction of template arguments from a
function call expression goes, some familiar techniques can give
surprising results. For example, the extensively studied in this
article function template <tt class="classname">bind2nd</tt> is
written in such a way that it does not allow either of its template
parameters <tt class="literal">BinOp</tt> and <tt class=
"literal">T</tt> to be deduced to be a const-qualified type. Think
about it. The same is true of, for example, the function template
<tt class="classname">make_pair</tt> from the standard header
<tt class="filename">utility</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e1447" id=
"d0e1447"></a>Conclusion</h2>
</div>
<p>The three cases that I explained in this article are not the
only ones when the language uses template argument deduction. The
other cases of note are &quot;Deducing template arguments of a
conversion function template&quot;, &quot;Partial ordering of (member)
function templates&quot;, &quot;Deducing template arguments for explicit
instantiation of a (member) function template&quot;, and &quot;Referencing a
(member) function template specialization in a friend declaration&quot;.
Although not covered in this paper, these cases are based on the
same principles and I believe that the information given in this
article will assist the interested reader in mastering them, should
such a need arise. As a starting point I can say that the topics
&quot;Deducing template arguments for explicit instantiation of a
(member) function template&quot; and &quot;Referencing a (member) function
template specialization in a friend declaration&quot; are nearly
identical to what I explained in &quot;Deducing Template Arguments for
Explicit Specialization of a (member) Function Template.&quot;</p>
<p>In any case, I'm now working on a follow-up to this article
wherein I plan to give details of how things stand with respect to
&quot;Deducing template arguments of a conversion function template&quot; and
&quot;Partial ordering of function templates.&quot;</p>
<p>I welcome any feedback from readers, which you can send directly
to me at the address below.</p>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e1029" href="#d0e1029" id=
"ftn.d0e1029">1</a>]</sup> In fact, this is an important trait of
C++ that has a broader scope than deduction of template arguments
from a function call expression. The general rule is that before
being semantically analyzed every C++ expression that initially has
a reference type is converted to the underlying type of the
reference and is considered an lvalue. For example, given a
conforming compiler, the following piece of code will never trigger
the assertion:</p>
<pre class="programlisting">
int main() {
  int i, &amp; ri = i;
  assert(typeid(i) == typeid(ri));
}
</pre></div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
