title: Overloading + operator on generic class in C++
body: <p>I'm trying to overload the + operator in a forest class, a forest being a collection of trees, and the + operator is supposed to combine two forests into one.  I have the following code as my class definition:</p>
  
  <pre><code>template&lt;typename NODETYPE&gt;
  class Forest
  {
  
  
      public:
  
          friend Forest&amp; operator+&lt;&gt;(Forest&amp;, Forest&amp;);
          friend ostream&amp; operator&lt;&lt;&lt;&gt;(ostream&amp;, const Forest&amp;);
          friend istream&amp; operator&gt;&gt;&lt;&gt;(istream&amp;, Forest&amp;);
          Forest();
          Forest( const Forest&amp; otherForest);
          ~Forest();
          void nodes(int&amp;) const;
  
      private:
          ForestNode&lt;NODETYPE&gt; *root;
  
          ForestNode&lt;NODETYPE&gt; *getNewNode( const NODETYPE &amp;);
  };
  </code></pre>
  
  <p>The following is my implementation of operator+:</p>
  
  <pre><code>template&lt;typename NODETYPE&gt;
  Forest&amp; operator+&lt;&gt;(Forest&amp; f1, Forest&amp; f2)
  {
      f3 = new Forest();
      f3.root = *f1.*root;
      f3.root.sibling = *f2.*root;
      *f1.root = 0;
      *f2.root = 0;
      return f3;
  }
  </code></pre>
  
  <p>I get the following error on compile:</p>
  
  <pre><blockquote>|28|error: expected constructor, destructor, or type conversion before '&' token|</blockquote></pre>
  
  <p>line 28 refers to the signature of my operator+ implementation.</p>
  
  <p>I think to correct it i am supposed to add  to the return type, giving: </p>
  
  <pre><code>template&lt;typename NODETYPE&gt;
  Forest&lt;NODETYPE&gt;&amp; operator+&lt;&gt;(Forest&amp; f1, Forest&amp; f2)
  {
      f3 = new Forest();
      f3.root = *f1.*root;
      f3.root.sibling = *f2.*root;
      *f1.root = 0;
      *f2.root = 0;
      return f3;
  }
  </code></pre>
  
  <p>But that gives me the following errors:</p>
  
  <pre><blockquote>|28|error: declaration of 'operator+' as non-function|
  |28|error: missing template arguments before '&' token|
  |28|error: 'f1' was not declared in this scope|
  |28|error: missing template arguments before '&' token|
  |28|error: 'f2' was not declared in this scope|</blockquote></pre>
  
  <p>Can anyone help me with this?  I'd be very very thankful.</p>