C++——返回模板类型 vector 的函数

标签 c++ templates vector compilation

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/

相关文章:

c++ - 了解 C++ 中子类的类

c++ - `string s("hello") ;` and ` string s = "hello";` 有区别吗

c++ - 句柄的 Win API 包装器类

templates - 如何在 Symfony2 环境中注册另一个(自定义)Twig 加载器?

c++ - 了解 std::end() 的行为和 vector 中的内存分配

c++ - 从 C++ 中的其他方法调用构造函数

c++ - 模板类的赋值运算符

Java Play 2 - 模板化

c++ - 正确返回 vector 引用

r - 如何将矩阵的每一行除以R中向量的元素