Possible Duplicate:
Why can templates only be implemented in the header file?
我在编译返回模板类型 vector 的函数时遇到问题。如果我删除模板并替换为 double
,代码就会编译。 。此外,只有当函数定义和原型(prototype)不在同一文件中时才会出现此问题。我编译使用:
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
最佳答案
模板类不应拆分为 .hpp
和 .cpp
文件。
成员函数实现也必须包含在编译单元中(例如,您的 main.cpp
),否则编译器无法知道如何使用类型构建模板类您提供作为模板参数。您可以也可以在main.cpp
中#include "func.cpp"
,但这会很难看。
正如大卫建议的那样,https://stackoverflow.com/a/3040706/713961如果您好奇的话,可以为您提供更多信息。
关于C++——返回模板类型 vector 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14567450/