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


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 15, #3 - Jun 2003 + Francis' Scribbles from CVu journal</span></div>

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c108/">153</a>
                    (14)
<br />

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c181/">Francis' Scribbles</a>
                    (29)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c108-181/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c108+181/">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;Francis' Scribbles</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 June 2003 13:15:57 +01:00 or Fri, 06 June 2003 13:15:57 +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="d0e20" id="d0e20"></a></h2>
</div>
<p>You will have to wait to the end to understand that heading. The
story starts with one of the test students for my book who after
three days of bashing his head against a brick wall finally emailed
me with a problem that I could distil down to why this code will
not compile:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
using namespace std;
double distance(int, int);
int main() {
  int abc(0), xyz(0);
  cout &lt;&lt; distance(abc, xyz);
}
</pre>
<p>Try it. I can fix the problem this time by using <tt class=
"literal">::distance(abc, xyz)</tt>. But how on earth would an
inexperienced programmer know to try that? And how could anything
in the <tt class="literal">iostream</tt> header conceivably cause a
problem?</p>
<p>A little experience will lead you to guess that distance is used
as a function name somewhere in the Standard C++ Library. The error
messages generated (all five of them) will give you a clue that the
iterator header is part of the problem. Presumably the iostream
header includes that (and a little thought will show that that
inclusion is almost necessary).</p>
<p>The instinctive moral drawn by not a few C++ experts is that
that the above code just demonstrates the evils of using
directives. Sorry, I beg to differ. Suppose that your code needs to
use the distance function from the Standard C++ Library as well as
a distance function from a third party library. You might be of the
school of thought that prefers using declarations.</p>
<p>Try replacing the using directive in the above code with:</p>
<pre class="programlisting">
using std::cout;
using std::distance;
</pre>
<p>which is the style advocated by Andy Koenig in <i class=
"citetitle">Accelerated C++</i>. Now you get the same errors but
the only way to fix them is to remove the using <tt class=
"literal">std::distance;</tt> declaration.</p>
<p>As an aside, please note the difference between <tt class=
"literal">using</tt> declarations (that effectively make the name
concerned behave as if declared in the current scope) and
usingdirectives that simply make all the names in the specified
namespace available for overloading and for use without
qualification. A <tt class="literal">using</tt> directive is NOT
equivalent to providing using declarations for all the names
declared in the relevant <tt class="literal">namespace</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e61" id="d0e61"></a>The Next
Step</h2>
</div>
<p>Faced with, to me, unnatural behaviour from all the compilers I
had to hand (that for once all agreed with each other, Comeau,
CodeWarrior, Borland and MinGW) meant that I had to try to find out
what was happening.</p>
<p>First I looked up distance in my copy of Nico Josuttis <i class=
"citetitle">The C++ Standard Library</i>. Here I found:</p>
<pre class="programlisting">
template &lt;typename InputIterator&gt;
iterator_traits&lt;InputIterator&gt;::difference_type
  distance(InputIterator pos1,
           InputIterator pos2);
</pre>
<p>Well, the error messages mention <tt class=
"literal">iterator_traits</tt> so that looked as if I was moving
forward. But why was it trying to instantiate <tt class=
"literal">iterator_traits&lt;int&gt;</tt> for a template function
that could clearly never be called because an exactly matching
non-template function declaration was already in scope and must
always be preferred?</p>
<p>The answer to that question is simple: the compiler must
generate the overload set first before determining a best match.
That seems reasonable and avoiding special cases makes sense. But
why is it trying to place a function it cannot instantiate into the
overload set? Hang on to that question for a moment and have a look
at this code:</p>
<pre class="programlisting">
template &lt;typename T&gt;
class x_traits;

template&lt;typename T&gt;
x_traits&lt;T&gt;::return_type foo(T, T);

int foo(int, int);
int main(){
  foo(1, 2);
}
</pre>
<p>Do you think that code should compile? It does but only after I
remember to add <tt class="literal">typename</tt> before the return
type of the <tt class="literal">foo</tt> function template, without
a murmur and it selects the correct version of <tt class=
"literal">foo()</tt>. However notice that I have only declared
<tt class="literal">x_traits</tt>, I have not defined it. So what
happens when I add the definition? For example:</p>
<pre class="programlisting">
template &lt;typename T&gt;
class x_traits {
  typedef typename T::return_type return_type;
};
</pre>
<p>It depends where I place that definition. If I place it before
<tt class="literal">main()</tt>, the code fails to compile. If
after, everything is fine. In other words as long as the compiler
cannot try to instantiate the return type while generating an
overload set all will work as desired. However the moment we
provide that extra information, the compiler grabs it and refuses
to compile the code. Do you feel something is not quite right?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e106" id=
"d0e106"></a>Archaeological Research</h2>
</div>
<p>I am grateful to John Spicer of EDG for having dug away into the
past to find an explanation of what is clearly silly. Here is what
the C++ Standard has to say on the subject (and it took several
people quite a lot of winnowing down to find that this was the
problem):</p>
<div class="variablelist">
<dl>
<dt><span class="term">14.8.3 Overload resolution</span></dt>
<dd>
<p>A function template can be overloaded either by (non-template)
functions of its name or by (other) function templates of the same
name. When a call to that name is written (explicitly, or
implicitly using the operator notation), template argument
deduction (14.8.2) and checking of any explicit template arguments
(14.3) are performed for each function template to find the
template argument values (if any) that can be used with that
function template to instantiate a function template specialization
that can be invoked with the call arguments. For each function
template, if the argument deduction and checking succeeds,
<span class="bold"><b>the template-arguments (deduced and/or
explicit) are used to instantiate a single function template
specialization</b></span> which is added to the candidate functions
set to be used in overload resolution. <span class="bold"><b>If,
for a given function template, argument deduction fails, no such
function is added to the set of candidate functions for that
template.</b></span> ...</p>
</dd>
</dl>
</div>
<p>I have emphasised two sections.</p>
<p>In 1996 clause 14 of what was to become the C++ Standard was
being reworked editorially. One of the changes made was to
systematically replace 'generate' with 'instantiate' and another
was to replace 'template function' with 'function template
specialization'. These were perfectly sensible editorial changes
because 'generate' was almost always used as synonym for
'instantiate', and there is no such beast as a 'template
function.'</p>
<p>Before that date the first piece of emphasized text read:
&quot;<span class="quote">the template-arguments (deduced and/or
explicit) are used to generate a single template
function</span>&quot;</p>
<p>That is substantially more vague and would not have led
implementors to try to actually instantiate the function rather
than just use its signature. Those two substitutions were generally
benign but together leads to the current position where many high
quality compilers are rejecting the code I started with.</p>
<p>However the second piece of emphasised text leads to looking
further to understand what it means to say that 'argument deduction
fails.' This leads to14.8.2/4, which explicitly says: &quot;<span class=
"quote">When all template arguments have been deduced, all uses of
template parameters in non-deduced contexts are replaced with the
corresponding deduced argument values. If the substitution results
in an invalid type, as described above, type deduction
fails.</span>&quot;</p>
<p>The problem is that the failure occurs whilst the compiler is
trying to instantiate a template because that is the only way that
it can follow the requirements of 14.8.2. But why are compilers
treating that failure as making the users source ill-formed? I do
not think that the compilers are doing the right thing here. If I
understand the text correctly, the very first error in trying to
instantiate the return type should cause the compiler to silently
remove the function template from the list of overload
candidates.</p>
<p>That means that compiler implementors have to be more careful of
the context in which a template instantiation is taking place.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e142" id="d0e142"></a>Is This the
End of the Story?</h2>
</div>
<p>I think not. 14.8.2's requirements re generating an overload
have some serious things to say about <tt class=
"literal">export</tt>.</p>
<p>In order to determine if argument deduction for a function
template such as <tt class="literal">std::distance</tt> has
succeeded the compiler has to see the relevant template
definitions. For example consider:</p>
<pre class="programlisting">
template &lt;typename T&gt;
class x_traits;

template&lt;typename T&gt;
x_traits&lt;T&gt;::return_type &amp; foo(T, T);
int foo(int, long);
int main(){
  foo(1, 2);
}
</pre>
<p>Now <tt class="literal">foo&lt;int&gt;</tt> is the best match if
it is allowed to be part of the overload set. However under the
requirements of 14.8.2/4 it should not be considered if <tt class=
"literal">x_traits&lt;int&gt;</tt> cannot be instantiated. However
the compiler cannot know the answer to that question until it can
see the definition of <tt class="literal">x_traits</tt>.</p>
<p>Under the inclusion model for templates that will not happen (I
think) but once we bring <tt class="literal">export</tt> into play
all the bets are off.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e173" id=
"d0e173"></a>Conclusion</h2>
</div>
<p>This all started because a novice was faced with code that would
not work. That happened because I, as an author, had checked my
code, moved on, re-organised a library and did not check that the
re-organisation had not broken anything. I knew in my own mind that
it could not have done. In one sense I was right, because it should
not have done but that is not really an excuse.</p>
<p>I guess that this was not the first time that the issue has
arisen somewhere during the last five years. I guess that it has
just been treated as a reason for avoiding using directives (and
possibly declarations).</p>
<p>We all know that C++ templates are problematical and so we do
not make enough effort to understand when things go wrong. I think
we do have a real problem hiding within the novice's code not
compiling. I think we have to address that problem. I do not think
that it is going to prove at all easy.</p>
<p>I think that there is a subtle but serious break in the overload
rules when function templates that have templated types dependant
on their deduced type arguments. I would hate to be a compiler
implementor faced with this problem but I think that we should not
just dismiss it.</p>
<p>It is a fundamental precept of programming in C++ that the
meaning of code should not silently change because we make a
definition visible. In my opinion the current rules for overload
resolution break that precept.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
