title: C++ -- Function returning vector of template type
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file">Why can templates only be implemented in the header file?</a>  </p>
  </blockquote>
  
  
  
  <p>I am having trouble compiling a function that returns a vector of template type. The code compiles if I remove the template and replace with <code>double</code>. Also, this problem only occurs if the function definition and prototype are not in the same file. I compile using:</p>
  
  <pre><code>g++ func.cpp main.cpp
  </code></pre>
  
  <p>main.cpp:</p>
  
  <pre><code>#include &lt;vector&gt;
  #include "func.h"
  
  int main(int argc, char** argv)
  {
      double x_min = 0.0;
      double x_max = 1.0;
      int N = 20;
      std::vector&lt;double&gt; x = linspace(x_min,x_max,N);
  
      return 0;
  }
  </code></pre>
  
  <p>func.cpp:</p>
  
  <pre><code>#include "func.h"
  
  template &lt;class T&gt;
  std::vector&lt;T&gt; linspace(T x1, T x2, int N)
  {
      std::vector&lt;T&gt; x(N);
      if(N == 1)
      {
          x[0] = x2;
          return x;
      }
  
      T delta_x = (x2-x1)/(N-1);
  
      for(int ii = 0; ii &lt; N; ii++)
      {
          x[ii] = x1 + ii*delta_x;
      }
  
      x[N-1] = x2;
      return x;
  }
  </code></pre>
  
  <p>func.h:</p>
  
  <pre><code>#include &lt;vector&gt;
  
  template &lt;class T&gt;
  std::vector&lt;T&gt; linspace(T x1, T x2, int N);
  </code></pre>
  
  <p>The compiler produces the following output:</p>
  
  <pre><code>/tmp/cclptwq7.o: In function `main':
  main.cpp:(.text+0x45): undefined reference to `std::vector&lt;double, std::allocator&lt;double&gt; &gt; linspace&lt;double&gt;(double, double, int)'
  collect2: ld returned 1 exit status
  </code></pre>