【问题标题】:C++ -- Function returning vector of template type [duplicate]C ++ - 函数返回模板类型的向量[重复]
【发布时间】: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


    【解决方案1】:

    不应将模板类拆分为 .hpp.cpp 文件。

    成员函数实现也必须包含在编译单元中(例如,您的main.cpp),否则编译器无法知道如何使用您作为模板参数提供的类型构建模板类。您也可以main.cpp 中使用#include "func.cpp",但这会很丑。

    正如 David 所建议的,https://stackoverflow.com/a/3040706/713961 会为您提供更多信息,如果您有兴趣的话。

    【讨论】:

    • 技术上不正确。他们可以,只要你做得正确,并接受它所暗示的限制。通常,人们不会这样做,因为涉及到所有的权衡,但它可以做到。 :)
    【解决方案2】:

    模板必须在同一个文件中定义,否则会出现链接器错误。请参阅this answer 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2015-07-20
      • 2018-04-06
      • 1970-01-01
      相关资源
      最近更新 更多