    <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  :: Student Code Critique Competition</title>
        <link>https://members.accu.org/index.php/articles/1201</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">Student Code Critiques from CVu journal. + CVu Journal Vol 14, #5 - Oct 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/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</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/c77/">CVu</a>

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+112/">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;Student Code Critique Competition</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 October 2002 13:15:55 +01:00 or Sun, 06 October 2002 13:15:55 +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><span class="bold"><b>Prizes provided by Blackwells Bookshops
&amp; Addison-Wesley</b></span></p>
<p><span class="emphasis"><em>Please note that participation in
this competition is open to all members. The title reflects the
fact that the code used is normally provided by a student as part
of their course work.</em></span></p>
<p><span class="emphasis"><em>Note that this item is part of the
Dialogue section of C Vu which is intended to designate it as an
item where reader interaction is particularly important. Readers'
comments and criticisms of published entries are always
welcome.</em></span></p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e29" id="d0e29"></a>Student Code
Critique 17: The Entries</h2>
</div>
<p><span class="emphasis"><em>Last time I asked for a critique of
the following short program.</em></span></p>
<pre class="programlisting">
template &lt;int N&gt; 
class T { 
  public: friend T operator+(const T&amp;, const T&amp;);
  private data[N + 1]; };
template &lt;int N&gt; 
T&lt;N&gt; operator+(const T&lt;N&gt;&amp; S1, const T&lt;N&gt;&amp; S2) {
  return S1;
}
int main(){
  T&lt;64&gt; a, b, c = a + b; 
}
</pre>
<p><span class="emphasis"><em>The critique was to include more than
just identification and correction of errors. I wanted to see
positive advice to the student on how better to achieve the
objective. When I set the problem I realised that it would actually
be rather more demanding than some of the earlier critiques. That I
was right in this is illustrated by the fact that I only received
three submissions. It is a pity that only one in four hundred
members can manage to submit a solution. Yes, I know about time,
but this was summer for most of you. Perhaps lying around on sun
washed beaches is more attractive. Interestingly the three entries
all come from outside the UK (India, US and Norway) and those
members have less time to enter than those in the
UK.</em></span></p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e40" id="d0e40"></a>From Gurusami
Annamalai <tt class="email">&lt;<a href=
"mailto:d0253028@ncb.ernet.in">d0253028@ncb.ernet.in</a>&gt;</tt></h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e45" id="d0e45"></a>Need for a
template parameter</h3>
</div>
<p>The first question that needs to be asked is &quot;Is there a need to
make the class T a template?&quot; This question is important because,
when we make a class a template, and there are too many instances
of the template, then the space complexity of the resultant object
code would increase. Paraphrased, improper usage of template class
would lead to code bloat.</p>
<p>There is a more fundamental issue here. For example, in the
above program, if the template parameter, specifies only the
attributes of objects, rather than their behaviour, then its better
made a member variable of the class, and the value could be
assigned in the constructor. This means that, if</p>
<pre class="programlisting">
T&lt;25&gt; t1;
T&lt;50&gt; t2;
</pre>
<p>behave the same (only their state differ), then the usage of
templates is not justified.</p>
<p>I'll assume that class T being a template is justified and
proceed further.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e58" id="d0e58"></a>Specifying the
access modifiers</h3>
</div>
<p>When we specify an access modifier, like <tt class=
"literal">public:</tt> etc, it doesn't apply to one member of the
class. Rather it applies to all the members of the class that are
declared after the modifier, either till the end of the class
declaration, or the occurrence of another access modifier,
whichever is earlier. Because of this semantics, it would be more
self-descriptive if the access modifier is specified in a line by
itself, followed by the members which it qualifies.</p>
<p>For example, it is better to write</p>
<pre class="programlisting">
public:
  friend T operator+(const T&amp;, const T&amp;);
</pre>
<p>than</p>
<pre class="programlisting">
public: friend T operator+(const T&amp;,
                           const T&amp;);
</pre>
<p>The latter somehow gives the feeling that it applies only to the
member along which it appears; the former, is self documenting. It
seems to say that the following members are public. As a bonus, the
former style helps to avoid errors like the one in the program,
(reproduced below)</p>
<pre class="programlisting">
private data[N + 1]; // data type missing
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e78" id="d0e78"></a>Operator
Overloading</h3>
</div>
<p>While overloading an operator (like `+') for a user-defined data
type, it is better kept as a member function of that class, unless
the left operand of the operator being overloaded is of a different
class. In that case, a friend function would be used.</p>
<p>In the above program we have</p>
<pre class="programlisting">
T operator+ (const T&amp;, const T&amp;);
                      // friend function
</pre>
<p>Since the left hand operand of the operator (the first
parameter) is a reference to an object of the class, for which we
are overloading the operator, this function is best made a member
function of the relevant class (here it is T). So we should prefer
the following in place of the above.</p>
<pre class="programlisting">
T operator+ (const T&amp;); // member function
</pre>
<p>Suppose we want to do something like</p>
<pre class="programlisting">
T&lt;25&gt; p;
int j;
T&lt;25&gt; r = j + p;
</pre>
<p>then we would need,</p>
<pre class="programlisting">
T&lt;N&gt; operator+(const int&amp;, const T&lt;N&gt;&amp;);
</pre>
<p>which cannot be converted to be used as a member of template
class T. Only in such cases friend functions (to overload
operators) are to be used.</p>
<p>The classic example to demonstrate this requirement is the
overloading of <tt class="literal">operator&lt;&lt;</tt> to work
with the <tt class="literal">ostream</tt> object <tt class=
"literal">cout</tt>. Of course, there are other examples, but I
have given one.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e112" id="d0e112"></a>Making friends
with template function</h3>
</div>
<p>The declaration,</p>
<pre class="programlisting">
friend T operator+(const T&amp;, const T&amp;);
</pre>
<p>taking account of its context in the above program, is the same
as</p>
<pre class="programlisting">
friend T&lt;N&gt; operator+(const T&lt;N&gt;&amp;, const T&lt;N&gt;&amp;);
</pre>
<p>This, in spite of our best intentions, doesn't make any friends.
This is because we are looking for a non-template function with
name &quot;<tt class="literal">operator+</tt>&quot;, which doesn't exist.
(g++ compiler, version 2.96, warned me of this!</p>
<p>The above declaration should be</p>
<pre class="programlisting">
friend T&lt;N&gt; operator+&lt;N&gt;(const T&lt;N&gt;&amp;,
                         const T&lt;N&gt;&amp;);
</pre>
<p>which can be simplified as, again taking account of its context
in the above program,</p>
<pre class="programlisting">
friend T operator+&lt;N&gt;(const T&amp;, const T&amp;);
</pre>
<p>and further to,</p>
<pre class="programlisting">
friend T operator+&lt;&gt;(const T&amp;, const T&amp;);
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e140" id="d0e140"></a>Fixing the above
program</h3>
</div>
<p>By fixing the above program we get,</p>
<pre class="programlisting">
template&lt;int N&gt;
class T {
public:
  friend T operator+&lt;&gt; (const T&amp;, const T&amp;);
private:
  int data[N + 1]; // int or anything
};

template &lt;int N&gt;
T&lt;N&gt; operator+(const T&lt;N&gt;&amp; S1, const T&lt;N&gt;&amp;S2){
  return S1;
}

int main() {
  T&lt;64&gt; a, b, c = a + b;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e147" id="d0e147"></a>The idiomatic
way</h3>
</div>
<p>The better way to write the above code is,</p>
<pre class="programlisting">
template&lt;int N&gt;
class T {
public:
  T operator+(const T&amp;); // member function
private:
  int data[N + 1];
};

template&lt;int N&gt;
T&lt;N&gt; T&lt;N&gt;::operator+ (const T&lt;N&gt;&amp; S1){
  return *this;
// first parameter in given program
}
 
int main() {
  T&lt;64&gt; a, b, c = a+b;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e154" id="d0e154"></a></h3>
</div>
<p><span class="emphasis"><em>Note that Annamalai is a student in
Bangalore. Until today, his was the only submission, which left me
somewhat worried because I am not sure he has exactly pinned down
the problem. Then the following arrived in my
email:</em></span></p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e159" id="d0e159"></a>From
Christopher Currie <tt class="email">&lt;<a href=
"mailto:christopher@currie.com">christopher@currie.com</a>&gt;</tt></h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e164" id="d0e164"></a>Syntax
Errors</h3>
</div>
<p>Though the goal was to comment on C++ idioms, there are some
syntax errors that will need to be corrected first, before the code
can even be compiled. The original code, as printed, with line
numbers added for clarity:</p>
<pre class="programlisting">
1   template &lt;int N&gt; 
2   class T { 
3   public: friend T operator+(const T&amp;, 
4                              const T&amp;); 
5   private data[N + 1]; 
6   }; 
7   template &lt;int N&gt; 
8   T&lt;N&gt; operator+ (const T&lt;N&gt;&amp; S1, 
9                   const T&lt;N&gt;&amp; S2) { 
10    return S1; 
11  } 
12  int main() { 
13    T&lt;64&gt; a, b, c = a + b; 
14  }
    
</pre>
<p>The syntax errors are in the declaration of data; the omission
of a colon after <tt class="literal">private</tt> and the lack of a
data type. Access control keywords like <tt class=
"literal">private</tt> and <tt class="literal">public</tt> are not
to be confused with type modifiers such as <tt class=
"literal">const</tt>. They are labels that affect the access of all
the declarations that follow them. For this reason, it is good
style to keep them on lines of their own:</p>
<pre class="programlisting">
1  template &lt;int N&gt; 
2  class T { 
3    public: 
4      friend T operator+(const T&amp;, 
5                         const T&amp;); 
6    private: 
7      data[N + 1]; 
8  }; 
</pre>
<p>Now we can clearly see the other problem with data, the lack of
a data type. Legacy C compilers allowed identifiers to be
implicitly <tt class="literal">int</tt> in the absence of a type
declaration. Although some C++ compilers allow it, this is not
valid C++.</p>
<pre class="programlisting">
7      int data[N + 1];
</pre>
<p>Now the code will compile, but it will not link. The reason is
subtle, and the answer in this case covers many points of style
that code borrows from textbook examples. As we clean up the style
of the example, hopefully the answer will become clear.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e196" id="d0e196"></a>Class Names
&amp; Template Parameters</h3>
</div>
<p>A major source of confusion in the class is the use of T as an
identifier. T is (over)used in books on template programming, most
commonly to represent the type of the template parameter. In this
case, the template parameter is not a type, it is an integral
value. This illustrates the importance of using parameter names and
class names that represent the purpose of the class or parameter.
In this example, there is not enough context to know the purpose of
this class, so we'll use the name <tt class=
"literal">FixedBuffer</tt> for the class, and <tt class=
"literal">length</tt> for the template parameter.</p>
<pre class="programlisting">
template &lt;size_t length&gt; 
class FixedBuffer { 
public: 
  friend FixedBuffer operator+( 
      const FixedBuffer&amp;, const FixedBuffer&amp;); 
private: 
  int data[length + 1];
};
template &lt;size_t length&gt; 
FixedBuffer&lt;length&gt; operator+(
        const FixedBuffer&lt;length&gt;&amp; S1, 
        const FixedBuffer&lt;length&gt;&amp; S2){ 
  return S1; 
} 
int main() {
  FixedBuffer&lt;64&gt; a, b, c = a + b; 
}    
</pre>
<p>This looks better, but now that the obscuring type names are
gone, you might notice that the two <tt class=
"literal">operator+</tt> functions look a little different...</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e214" id="d0e214"></a>Friend
Functions</h3>
</div>
<p>From the C++ specification:</p>
<p>&quot;<span class="quote">&quot;When a template is instantiated, the names
of its friends are treated as if the specialization had been
explicitly declared at its point of instantiation.&quot;</span>&quot;</p>
<p>In our code, the function is treated as if it was declared as it
appears in the friend function declaration. This draws attention to
what the friend function is saying. As is common in template
classes, the compiler does not require that you include the
template parameters when using the class name within its
declaration. The precise declaration would read:</p>
<pre class="programlisting">
template &lt;size_t length&gt; 
class FixedBuffer { 
public: 
  friend FixedBuffer&lt;length&gt; operator+( 
        const FixedBuffer&lt;length&gt;&amp; S1, 
        const FixedBuffer&lt;length&gt;&amp; S1); 
... 
}; 
</pre>
<p>But since it is within a template declaration, the name lookup
doesn't happen until the class template is instantiated. When our
class declared in main, it's template declares a friend function
that looks like:</p>
<pre class="programlisting">
FixedBuffer&lt;64&gt; operator+( 
        const FixedBuffer&lt;64&gt;&amp; S1, 
        const FixedBuffer&lt;64&gt;&amp; S1);
</pre>
<p>Aha! This is not a template function! This is why the program
will not link, for the signature of this function does not match
the template function that is defined later in the code. In this
case, one correct declaration would be:</p>
<pre class="programlisting">
template &lt;size_t length&gt; 
class FixedBuffer { 
public: 
  friend FixedBuffer operator+&lt;length&gt;( 
                   const FixedBuffer&amp; S1, 
                   const FixedBuffer&amp; S1); 
... 
};
    
</pre>
<p>(There is another syntax that my compiler accepts that requires
that you declare the function before defining the class. I prefer
the above.) This designates <tt class="literal">operator+</tt> as a
template function, and shows that the concrete instance of the
template function that has a matching length template parameter is
the actual friend.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e239" id="d0e239"></a>Idiomatic
usage</h3>
</div>
<p>Wow, all these rules for template friends of template classes
are hard! Fortunately, there is a better way. The important point
to realize is that <tt class="literal">operator+</tt> doesn't have
to be a <tt class="literal">friend</tt>! Think about the
following:</p>
<pre class="programlisting">
int a, b, c; 
// ... assign values 
a = b + c;
</pre>
<p>Are b and c any different after the assignment than before? Of
course not. The calculated result doesn't affect either of its
parameters. In fact, we can't change either parameter, because its
arguments are (as in this case) almost always <tt class=
"literal">const</tt>! The few operations that need rights to change
an operand include the assignment operators and their kin, and
these are almost always member functions that don't need to be
friends anyway.</p>
<pre class="programlisting">
template &lt;size_t length&gt; 
class FixedBuffer { 
public: 
  FixedBuffer&amp; operator+=( const FixedBuffer&amp; rhs){ 
    // ...add rhs to *this 
    return *this; 
  } 
... 
};    
</pre>
<p>This code illustrates the canonical definition of the
add-and-assign operator that takes its right hand argument as an
operator, and returns a reference to itself, allowing the result to
be used as an r-value (in other words, you can add the result to
other variables, use it as a function argument, etc.). We've
contained the code for adding <tt class="literal">FixedBuffer</tt>
types within a member function, without any complicated <tt class=
"literal">friend</tt> functions. Now, instead of duplicating that
code in <tt class="literal">operator+</tt>, we'll simply reuse it
in the canonical definition of addition:</p>
<pre class="programlisting">
template &lt;size_t length&gt;
FixedBuffer&lt;length&gt; operator+( 
               const FixedBuffer&lt;length&gt;&amp; S1,
               const FixefBuffer&lt;length&gt;&amp; S2){ 
  FixedBuffer&lt;length&gt; temp(S1); 
  temp += S2; 
  return temp; 
} 
</pre>
<p>This very neatly allows us to change the definition of
<tt class="literal">operator+=</tt>, and get an updated definition
of <tt class="literal">operator+</tt> absolutely free. This is
typically the way most of the arithmetical operators are defined
for classes that need addition and subtraction to work the way that
we expect that integers do. Remember this need not only apply to
template classes; regular classes can benefit just as much from
this technique.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e280" id="d0e280"></a>Summary</h3>
</div>
<p>This deceptively small piece of code contained a lot of
complexity, and in our analysis we can deduce a couple general
rules. Remember, like all rules there are exceptions, but these
will give the student place from which to build experience:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>When a function needs to modify private or protected data within
a class, make that function a member function if at all
possible.</p>
</li>
<li>
<p>Define non-member, non-friend functions in terms of member
functions to maximize maintainability and correctness.</p>
</li>
</ol>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e292" id="d0e292"></a></h3>
</div>
<p><span class="emphasis"><em>I was about to put this column to bed
when the following arrived in my inbox.</em></span></p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e297" id="d0e297"></a>From Terje
Slettebo <tt class="email">&lt;<a href=
"mailto:tslettebo@chello.no">tslettebo@chello.no</a>&gt;</tt></h2>
</div>
<p>I've been waiting for a C++ entry, and finally, one came. :)</p>
<p>Also, since I unwittingly &quot;submitted&quot; a blooper (which ended up
as &quot;Problem 3&quot; in &quot;Francis' Scribbles&quot;, C Vu June &amp; August, :)
) let me try to &quot;remedy&quot; that by submitting this entry. By the way,
in the following discussion, I agreed with Francis, about the
problems with that code. It was originally intended to be just a
test of a calculation, as well, not a well- tested routine.
<span class="emphasis"><em>(Indeed you did, it just made a good
problem for my column because it gave me an excuse to write about
something I wanted to write about anyway. I am like that, scavenge
for bits wherever they may be found.</em></span>)</p>
<p>Regarding the given program. It says it can be compiled, but not
linked. However, there are syntax error that makes it not even
compile. These may be typos resulting from transferring the program
to the magazine, though.</p>
<p>There are quite a few problems with this code, so let me take
them in order:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Missing &quot;:&quot; after <tt class="literal">private.</tt></p>
</li>
<li>
<p>Missing type of data, <tt class="literal">int</tt> chosen
arbitrarily to fix it.</p>
</li>
<li>
<p>The <tt class="literal">operator+()</tt> doesn't make much
sense, as it just returns one of the operands.</p>
</li>
<li>
<p>More seriously, the <tt class="literal">friend</tt> declaration
declares a function, not a function template.</p>
</li>
</ol>
</div>
<p>Point 4 leads to the following problem: When it comes to
<tt class="literal">c=a+b</tt> it will have seen the following
declarations:</p>
<pre class="programlisting">
T&lt;64&gt; operator+(const T&lt;64&gt; &amp;,const T&lt;64&gt;  &amp;); 
// friend declaration only, instantiated 
// by the T&lt;64&gt;.
template&lt;int N&gt; 
T&lt;N&gt; operator+(const T&lt;N&gt; &amp;,const T&lt;N&gt; &amp;); 
// Declaration and definition 
</pre>
<p>Since the first is an exact match for <tt class=
"literal">c=a+b;</tt>, it won't instantiate the template, and you
get a link error.</p>
<p>The fix is easy enough: Make the <tt class="literal">friend</tt>
declaration a <tt class="literal">friend template</tt> declaration.
One also needs to provide a reasonable <tt class=
"literal">operator+()</tt> implementation:</p>
<pre class="programlisting">
template&lt;int N&gt; 
class T { 
public: 
  template&lt;int M&gt;
  friend T&lt;M&gt; operator+(const T&lt;M&gt; &amp;, 
                        const T&lt;M&gt; &amp;); 
private: 
  int data[N+1]; 
}; 
template&lt;int N&gt; 
T&lt;N&gt; operator+(const T&lt;N&gt; &amp;S1,const T&lt;N&gt; &amp;S2){ 
  T&lt;N&gt; temp; 
  for(int i=0;i!=N;++i) 
    temp.data[i]=S1.data[i]+S2.data[i]; 
  return temp; 
} 
</pre>
<p>As another comment, in general, &quot;T&quot; doesn't appear to be a very
meaningful class name, either, but it's hard to tell, without
knowing the context.</p>
<p>OK. On to the alternative. The article said &quot;I want suggestions
for coding idioms that will make the student's life easier,&quot; so
let's see what we can do. A common idiom is to implement an
operator in terms of the assignment-version of the operator. See
for example [<a href=
"#more-effective-cpp">more-effective-cpp</a>].</p>
<p>In the case above, <tt class="literal">operator+()</tt> could be
a member function, but if you have an operator where the left-hand
argument is another type, then it has to be a global function. So
let's design a class for this general case, making the operator a
global function. We'll also make a sensible <tt class=
"literal">operator+=()</tt> implementation, that <tt class=
"literal">operator+()</tt> will use. The compiler-generated copy
constructor does the right thing, so none is provided, and other
constructors are omitted, for brevity, and since they didn't appear
in the original:</p>
<pre class="programlisting">
template&lt;int N&gt; 
class T { 
public: 
  T &amp;operator+=(const T  &amp;other){ 
    for(int i=0;i!=N;++i) 
      data[i]+=other.data[i]; 
      return *this; 
  }
private: 
  int data[N+1]; 
}; 
template&lt;int N&gt; 
T&lt;N&gt; operator+(const T&lt;N&gt; &amp;S1,const T&lt;N&gt; &amp;S2){ 
  return T&lt;N&gt;(S1)+=S2; 
}
int main() { 
  T&lt;64&gt; a,b,c=a+b; 
} 
</pre>
<p>This has a number of advantages over the first one:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>By providing both += and +, you let the user of the class decide
which to use, knowing that the former is generally more efficient,
as it avoids creating a temporary object.</p>
</li>
<li>
<p>By implementing + in terms of +=, you ensure a consistent
behaviour (and expected efficiency) for the two operators. The
operation only needs to be implemented in +=, and you essentially
get + &quot;for free.&quot;</p>
</li>
<li>
<p>An important point is that you don't need any <tt class=
"literal">friend</tt> declaration, unlike the first version.
<tt class="literal">operator+()</tt> needs no special access to T,
as it only uses the public interface.</p>
</li>
<li>
<p>By implementing the <tt class="literal">operator+()</tt> as a
general template, you may actually use it for several classes.
Here, we only implement it for the class T, though.</p>
</li>
</ol>
</div>
<p>Some details about the implementation:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>As given in [<a href=
"#more-effective-cpp">more-effective-cpp</a>], by using an unnamed
temporary in the function template (rather than <tt class=
"literal">T&lt;N&gt; temp(S1); S1+=S2; return temp;</tt>), we make
it possible for the compiler to perform the return value
optimisation (eliminating the creation of any temporaries, by
constructing the result at the call site), which may be available
in more compilers, than the more recent named return value
optimisation.</p>
</li>
<li>
<p>It may be debated if <tt class="literal">operator+=()</tt>
should return <tt class="literal">T&amp;</tt> or <tt class=
"literal">const T &amp;</tt>. However, the advice in [<a href=
"#effective-cpp">effective-cpp</a>] and precedence in the standard
is to use <tt class="literal">T&amp;</tt>, so that's what is used
here. The rationale is basically to &quot;do as the ints do.&quot;</p>
</li>
</ul>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e436" id="d0e436"></a>References:</h2>
</div>
<div class="bibliomixed"><a name="more-effective-cpp" id=
"more-effective-cpp"></a>
<p class="bibliomixed">[more-effective-cpp] Scott Meyers
<span class="citetitle"><i class="citetitle">More Effective
C++</i></span>, &quot;Item 22: Consider using op= instead of stand-alone
op.&quot;</p>
</div>
<div class="bibliomixed"><a name="effective-cpp" id=
"effective-cpp"></a>
<p class="bibliomixed">[effective-cpp] Scott Meyers <span class=
"citetitle"><i class="citetitle">Effective C++</i></span>, &quot;Item
15: Have operator= return a reference to *this.&quot;</p>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e449" id="d0e449"></a>The Winner of
SCC 17</h2>
</div>
<p>The editor's choice is Christopher Currie.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e454" id="d0e454"></a>Student Code
Critique 18</h2>
</div>
<p><span class="emphasis"><em>I have taken particular care not to
introduce typos into this piece and I have quoted the first part of
a twenty-line error message, not least because it is less than
helpful. The specific problem is one that you either see straight
away or that will take you an embarrassingly long time to identify.
However there are a number of other points that should be spotted
and commented on. Remember you should never allow your students to
go away with no more than the instant fix they
seek.</em></span></p>
<p>I am trying to compile the following code and getting error that
I don't understand.</p>
<p>In file <tt class="filename">pgsimeta.h</tt></p>
<pre class="programlisting">
#include &lt;vector&gt; 
namespace PGSIMeta { 
class PgsiMeta { 
public: 
  PgsiMeta(); 
  virtual ~PgsiMeta(); 
  bool operator==(const PgsiMeta); 
private: 
// MetaData is a class defined at the top 
  typedef vector&lt;MetaData&gt; 
  DataList; DataList dataList; 
}; 
}
</pre>
<p>In file <tt class="filename">pgsimeta.cp</tt></p>
<pre class="programlisting">
#include &quot;pgsimeta.h&quot; 
using PGSIMeta; 
bool PgsiMeta::operator==(
                const PgsiMeta&amp; obj){ 
  return dataList == obj.dataList; 
}
</pre>
<p>Here is the error compiling:</p>
<p><tt class="computeroutput">_pgsi_meta.h:51: PGSIMeta::operator==
(const PGSIMeta::PgsiMeta &amp;)' must take exactly two
arguments</tt></p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
