title: Friend function in template class
body: <p>I'm trying to make the multiplication operator a friend of a template class named TVector3. I have read that I could make a forward declaration of the friend function before declaring it in the class declaration however my attempts of doing so were futile. I know I could simply define the friend function instead of declaring it, but I want it to work with forward declaration technique.</p>
  
  <p>In particular I was trying to implement <a href="http://www.parashift.com/c++-faq-lite/template-friends.html" rel="nofollow noreferrer">this</a> solution for my case. I found <a href="https://stackoverflow.com/questions/4660123/overloading-friend-operator-for-template-class/4661372#4661372">this</a> post too were David Rodriguez gives a solution (the third version) but I don't know what I'm doing wrong.</p>
  
  <p>I compile using '<em>g++ template.cpp tempmain.cpp a</em>' and The compiler (g++) gives the following error:</p>
  
  <p><strong>undefined reference to 'ray::TVector3 ray::operator*(float, ray::TVector3 const&amp;)'</strong></p>
  
  <p>for the following code:</p>
  
  <p>template.h:</p>
  
  <pre><code>#ifndef TVECTOR_H
  #define TVECTOR_H
  
  #include &lt;cmath&gt;
  
  namespace ray
  {
      //forward declarations
      template &lt;class T&gt; class TVector3;
      template &lt;class T&gt; TVector3&lt;T&gt; operator* (T, const TVector3&lt;T&gt; &amp;);
  
      template &lt;class T&gt;
      class TVector3 {
  
          public:
              union {
                  struct {
                      T x, y, z;
                  };
                  T xyz[3];
              };
  
          //function needed
          friend TVector3&lt;T&gt; operator*&lt;T&gt; (T, const TVector3&lt;T&gt; &amp;);
      };
  
  }
  
  #endif
  </code></pre>
  
  <p>template.cpp:</p>
  
  <pre><code>#include "template.h"
  
  using namespace ray;
  
  //friend operator function
  template&lt;class T&gt; TVector3&lt;T&gt; operator * (T f, const TVector3&lt;T&gt; &amp;v)
  {
      return TVector3&lt;T&gt;(f * v.x, f * v.y, f * v.z);
  }
  
  //instantiate template of type float
  template class TVector3&lt;float&gt;;
  </code></pre>
  
  <p>tempmain.cpp:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "template.h"
  
  int main()
  {
      ray::TVector3&lt;float&gt; v1, v2;
  
      v2.x = 3;
      v1 = 4.0f * v2; //this reports as undefined
  
      std::cout &lt;&lt; v1.x &lt;&lt; "\n";
  
      return 0;
  }
  </code></pre>
  
  <p>That is the full source code. What am I doing wrong?</p>