首页 > 解决方案 > 从类中的模板函数调用模板函数

问题描述

我正在尝试使用类中模板函数中的模板函数。我在类 Sort.h 中有以下代码:

class Sort {
public:
    Sort();
    virtual ~Sort();
    template <typename T>
    static std::vector<T> merge (std::vector<T> array, int p, int q, int r);
    template <typename T>
    static std::vector<T> merge_sort(std::vector<T> array, bool ascending);
};

template <typename T>
std::vector<T> merge (std::vector<T> array, int p, int q, int r){
    std::vector<T> L = std::vector<T>(array.begin() + p, array.begin() + q + 1);
    std::vector<T> R = std::vector<T>(array.begin() + q + 1, array.begin() + r + 1);
    T max = std::numeric_limits<T>::max();
    L.push_back (max);
    R.push_back (max);
    int j, k = 0;
    for (int i = p; i <= r; i++){
        if (L[j] <= R[k]){
            array[i] = L[j];
            j++;
        } else {
            array[i] = R[k];
            k++;
        }
    }
    return array;
}


template <typename T>
std::vector<T> Sort::merge_sort(std::vector<T> array, bool ascending){
    array = Sort::merge<T>(array, 0, 4, 9); // some random numbers
    return array;
} 

然后我尝试在 int main 中使用它:

std::vector<int> o = Sort::merge_sort<int>(input, 1);

其中“输入”只是一个 int 类型的向量。但我收到一个错误:

未定义的引用std::vector<int, std::allocator<int> > Sort::merge<int>(std::vector<int, std::allocator<int> >, int, int, int)

我不知道编译器为什么要寻找一个std::vector<int, std::allocator<int> >函数,它不应该寻找一个std::vector<int>函数吗?我怎样才能使这项工作?谢谢!

标签: c++templates

解决方案


merge您不小心声明了一个不属于Sort该类的单独函数。

代替

template <typename T>
std::vector<T> merge ( ...

你需要:

template <typename T>
std::vector<T> Sort::merge ( ...

推荐阅读