Reputation: 113
I am trying to use a template function from a template function in a class. I have the following code in class 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;
}
And then I try to use it in int main as:
std::vector<int> o = Sort::merge_sort<int>(input, 1);
where "input" is simply a vector of int type. But I get an error:
undefined reference to
std::vector<int, std::allocator<int> > Sort::merge<int>(std::vector<int, std::allocator<int> >, int, int, int)
I don't know why the compiler is looking for an std::vector<int, std::allocator<int> >
function, shouldn't it look for an std::vector<int>
function instead? How can I make this work? Thank you!
Upvotes: 1
Views: 76
Reputation: 118681
You have accidentally declared a separate function called merge
that is not part of the Sort
class.
Instead of
template <typename T>
std::vector<T> merge ( ...
you need:
template <typename T>
std::vector<T> Sort::merge ( ...
Upvotes: 2