    <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  :: Alternatives for Partial Template Function
Specialisation</title>
        <link>https://members.accu.org/index.php/articles/385</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #50 - Aug 2002</span></div>

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

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

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

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

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

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

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

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+195/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Alternatives for Partial Template Function
Specialisation</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 August 2002 22:58:28 +01:00 or Fri, 02 August 2002 22:58:28 +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>Whilst template classes can be partially and wholly specialised,
template functions cannot. Alexandrescu [<a href=
"#Alexandrescu">Alexandrescu</a>] presents a technique to simulate
partial template function specialisation so that a uniform
interface is preserved, and calls to the template function(s) can
be made in a generic way. Key to the solution is a mapper type
which the client code must use in the function calls. This extra
'type-to-type' mapper rather clutters the interface with what you
might call an implementation detail. Here is a look at the original
proposal, followed by some possible alternatives.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e25" id="d0e25"></a>Original
Solution</h2>
</div>
<p>Overloaded template functions are at the heart of the
'specialisation'. A template struct is introduced (<span class=
"structname">Type2Type</span>) which serves as an identifier to
facilitate function lookup:</p>
<pre class="programlisting">
//from [<a href="#Alexandrescu">Alexandrescu</a>]:
template &lt;typename T&gt;
struct Type2Type {
  typedef T OriginalType;
};

template &lt;class T,class U&gt;
T* Create(const U&amp; arg, Type2Type&lt;T&gt;) {
  return new T(arg);
}

template &lt;class U&gt;
Widget* Create(const U&amp; arg,
               Type2Type&lt;Widget&gt;) {
  return new Widget(arg, -1);
}
</pre>
<p><tt class="function">Create()</tt> 'new's instances of
<tt class="classname">Widget</tt>s or instances of specific
<tt class="classname">Widget</tt>-derived things. The <tt class=
"classname">Widget</tt> class constructors have two arguments - the
second being an <tt class="type">int</tt> which should be set to
<tt class="literal">-1</tt>, and the derived classes' constructors
all have just a single argument - hence the need for
specialisation. The flavour of <span class=
"structname">Type2Type</span> which is passed to <tt class=
"function">Create()</tt> determines which overload to use. The
overload for the <tt class="classname">Widget</tt> class requires
<tt class="literal">Type2Type&lt;Widget&gt;</tt>, and the
completely generic version accepts <span class=
"structname">Type2Type</span> instances of <tt class=
"classname">Widget</tt>-derived types<sup>[<a name="d0e75" href=
"#ftn.d0e75" id="d0e75">1</a>]</sup>.</p>
<pre class="programlisting">
//test code
#include &lt;assert.h&gt;
struct WidgConfig {int i;};
struct Widget {
  Widget(const WidgConfig&amp; setup,
         int a) { assert(-1==a); }
};

struct SpecialWidget : Widget {
  SpecialWidget(
     const WidgConfig&amp; setup)
     : Widget(setup,-1) {}
};

WidgConfig cfg;
SpecialWidget* psw = Create(cfg,
Type2Type&lt;SpecialWidget&gt;());
Widget* wi = Create(cfg,
Type2Type&lt;Widget&gt;());
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e94" id="d0e94"></a>First
Alternative</h2>
</div>
<p>Alexandrescu initially suggests overloading by passing dummy
objects of the appropriate <tt class="classname">Widget</tt> type
rather than the <span class="structname">Type2Type</span> struct,
but then dismisses it as it requires the construction of
potentially superfluous objects, incurring the overhead of that
construction - and there's also the overhead of a pass-by-value to
consider:</p>
<pre class="programlisting">
//from [<a href="#Alexandrescu">Alexandrescu</a>]:
template &lt;class T, class U&gt;
T* Create (const U&amp; arg, T/*dummy*/) {
  return new T(arg);
}

template &lt;class U&gt;
Widget* Create (const U&amp; arg,
                Widget/*dummy*/) {
  return new Widget(arg, -1);
}
</pre>
<p>If <tt class="function">Create()</tt> is our only mechanism for
getting instances of <tt class="type">T</tt> or <tt class=
"classname">Widget</tt>, then we will have difficulty calling it
the first time when we don't yet have an instance to pass. With a
little tweaking, however, this does offer a feasible solution
without the problem of superfluous object creation. Pointer types
could be used to overload the function instead:</p>
<pre class="programlisting">
template &lt;class T, class U&gt;
T* Create (const U&amp; arg, T*/*dummy*/) {
  return new T(arg);
}

template &lt;class U&gt;
Widget* Create (const U&amp; arg,
                Widget*/*dummy*/) {
  return new Widget(arg, -1);
}
</pre>
<p>Pass a pointer of the appropriate type and the correct function
is called. No extra constructors or copy constructors are now being
called and the template function is effectively specialised.
Overloaded lookup can go ahead courtesy of an uncharacteristically
welcome <tt class="literal">NULL</tt> pointer, so there's no need
to worry about supplying a <tt class="classname">Widget</tt>
instance that we don't have yet:</p>
<pre class="programlisting">
SpecialWidget* pSwi =
  Create(cfg,
    reinterpret_cast&lt;SpecialWidget*&gt;(0));

Widget* pWid =
  Create(cfg,
    reinterpret_cast&lt;Widget*&gt;(0));
</pre>
<p>As an extra, this approach offers new possibilities as we now
have the option to pass a valid object, which can be exploited by
either overload. Imagine the <tt class="classname">Widget</tt>
class as a <tt class="classname">Window</tt> class:</p>
<pre class="programlisting">
template &lt;class U&gt;
Window* Create (const U&amp; arg,
                Window* parent) {
  if(parent) {
    Window* child =
             new Window(arg, -1, parent);
    return child;
  }
  else
    return new Window(arg, -1);
} // <sup>[<a name="d0e143" href="#ftn.d0e143" id=
"d0e143">2</a>]</sup>
</pre>
<p>This does offer an alternative style with extended flexibility,
and doesn't require the <span class="structname">Type2Type</span>
type.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e151" id="d0e151"></a>Second
Alternative</h2>
</div>
<p>Whilst template functions cannot be partially specialised, we
can partially specialise template classes<sup>[<a name="d0e156"
href="#ftn.d0e156" id="d0e156">3</a>]</sup>. It could help to make
use of the functor [<a href="#Stroustrup">Stroustrup</a>]
idiom:</p>
<pre class="programlisting">
template &lt;class T, class U&gt; 
struct Create {
  T* operator()(const U&amp; args) {
    return new T(args);
  }
};

template &lt;class T&gt; 
struct Create &lt;Widget, T&gt; {
  Widget* operator()(const T&amp; args) {
    return new Widget(args, -1);
  }
};
#
WidgConfig cfg;
SpecialWidget* psw =
 Create&lt;SpecialWidget,WidgConfig&gt;()(cfg);
Widget* pw =
 Create&lt;Widget,WidgConfig&gt;()(cfg);
</pre>
<p>Although the function calls to <tt class="function">Create</tt>
might look rather esoteric, this does also offer a generic
interface and dispels the need for extra types to be defined just
to solve the original problem:</p>
<pre class="programlisting">
template &lt;class T, class U&gt; 
struct Create {
  T* operator()(const U&amp; args) {
    return new T(args);
  }
};

template &lt;class T&gt; 
struct Create &lt;Widget, T&gt; {
  Widget* operator()(const T&amp; args) {
    return new Widget(args, -1);
  }
};
SpecialWidget* psw =
 Create&lt;SpecialWidget,WidgConfig&gt;()(cfg);
Widget* pw =
 Create&lt;Widget,WidgConfig&gt;()(cfg);
</pre>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e174" id="d0e174"></a>Footnotes &amp;
References</h2>
</div>
<div class="bibliomixed"><a name="Alexandrescu" id=
"Alexandrescu"></a>
<p class="bibliomixed">[Alexandrescu] Andrei Alexandrescu, Modern
C++ Design, Addison-Wesley, 2001 (section 2.5)</p>
</div>
<div class="bibliomixed"><a name="Stroustrup" id="Stroustrup"></a>
<p class="bibliomixed">[Stroustrup] Bjarne Stroustrup, The C++
Programming Language 3rd Ed., Addison-Wesley, 1997 (Section
18.4)</p>
</div>
</div>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e75" href="#d0e75" id=
"ftn.d0e75">1</a>]</sup> Microsoft Visual C++ 6.0 considers the
call to <tt class="literal">Create(cfg,
Type2Type&lt;Widget&gt;)</tt> to be ambiguous, so the code does not
port. Explicit template arguments are needed to coax it in the
right direction, but consistency in the interface is broken:</p>
<pre class="programlisting">
SpecialWidget* psw =
  Create&lt;SpecialWidget,
         WidgConfig&gt;(cfg,
             Type2Type&lt;SpecialWidget&gt;());
Widget* wi = Create&lt;WidgConfig&gt;(cfg,
             Type2Type&lt;Widget&gt;());
</pre>
<p>See MSDN Knowledge Base article Q240869 for bug description.
Also, if we try to specify explicit template arguments for the
other overload as well: <tt class=
"literal">Create&lt;SpecialWidget, WidgConfig&gt;(cfg,
Type2Type&lt;SpecialWidget&gt;())</tt>, then VC++ is unable to
match the overload, generating compiler bug C2665. Strangely, it
actually matches the lookup when you call it with <tt class=
"literal">Create&lt;SpecialWidget&gt;(cfg,
Type2Type&lt;SpecialWidget&gt;())</tt>.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e143" href="#d0e143" id=
"ftn.d0e143">2</a>]</sup> We still need to help Microsoft Visual
C++ 6.0 to know which function we want to call, by providing
explicit template arguments, so a generic and portable style is
lost.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e156" href="#d0e156" id=
"ftn.d0e156">3</a>]</sup> Microsoft Visual C++ 6.0 lacks support
for partial specialisation of template classes. See MSDN Knowledge
Base article Q240866. In that case each possible variation (i.e.
constructor) for the Widget class would have to be fully
specialised with a Create class of its own:</p>
<pre class="programlisting">
#ifdef __MSVC__
  template &lt;&gt;
  struct Create &lt;Widget, WidgConfig&gt; {
    Widget* operator()(
               const WidgConfig&amp; args) {
      return new Widget(args, -1);
    }
  };
// and any other complete
// specialisations needed...
#else
// Create &lt;Widget, T&gt; implementation
// as before
#endif
</pre></div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
