【发布时间】:2013-01-28 17:14:30
【问题描述】:
可能重复:
Why can templates only be implemented in the header file?
我在编译返回模板类型向量的函数时遇到问题。如果我删除模板并替换为double,代码将编译。此外,仅当函数定义和原型不在同一个文件中时才会出现此问题。我编译使用:
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);
编译器产生以下输出:
/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
【问题讨论】:
标签: c++ templates vector compilation