Possible Duplicate:
Why can templates only be implemented in the header file?
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 double. Also, this problem only occurs if the function definition and prototype are not in the same file. I compile using:
g++ func.cpp main.cpp
main.cpp:
#include <vector>
#include "func.h"
int main(int argc, char** argv)
{
double x_min = 0.0;
double x_max = 1.0;
int N = 20;
std::vector<double> x = linspace(x_min,x_max,N);
return 0;
}
func.cpp:
#include "func.h"
template <class T>
std::vector<T> linspace(T x1, T x2, int N)
{
std::vector<T> x(N);
if(N == 1)
{
x[0] = x2;
return x;
}
T delta_x = (x2-x1)/(N-1);
for(int ii = 0; ii < N; ii++)
{
x[ii] = x1 + ii*delta_x;
}
x[N-1] = x2;
return x;
}
func.h:
#include <vector>
template <class T>
std::vector<T> linspace(T x1, T x2, int N);
The compiler produces the following output:
/tmp/cclptwq7.o: In function `main':
main.cpp:(.text+0x45): undefined reference to `std::vector<double, std::allocator<double> > linspace<double>(double, double, int)'
collect2: ld returned 1 exit status
Template classes should not be split up into
.hppand.cppfiles.The member function implementations must be also be included in a compilation unit (for example, your
main.cpp), otherwise the compiler has no way of knowing how to build the template class with the types you provide as template arguments. You could also#include "func.cpp"inmain.cpp, but that would be ugly.As David suggested, https://stackoverflow.com/a/3040706/713961 gives you more information if you’re curious.