When I write a merge sort with recursion, I declared the mergeSort(T arr[], int n)
and inner one mergeSort(T arr[], int p, int r)
with a merge(T arr[], int p, int q, int r)
function in this order. And when I compile it the MSVC works OK, but g++ gives me output like this:
In file included from sortalgtest.cpp:1:0:
./sortalg.h: In instantiation of ‘void mergeSort(T*, int) [with T = int]’:
sortalgtest.cpp:8:61: required from here
./sortalg.h:193:14: error: no matching function for call to ‘mergeSort(int*&, int, int)’
mergeSort(arr, 0, n - 1);
~~~~~~~~~^~~~~~~~~~~~~~~
./sortalg.h:191:6: note: candidate: template<class T> void mergeSort(T*, int)
void mergeSort(T arr[], int n)
^~~~~~~~~
./sortalg.h:191:6: note: template argument deduction/substitution failed:
./sortalg.h:193:14: note: candidate expects 2 arguments, 3 provided
mergeSort(arr, 0, n - 1);
~~~~~~~~~^~~~~~~~~~~~~~~
I guess the cause might be the order of functions' declaration and I changed declaration order by calling. And this time g++ works too. What I want to know is why this works?
template <typename T>
void mergeSort(T arr[], int n)
{
mergeSort(arr, 0, n - 1);
}
template <typename T>
void mergeSort(T arr[], int p, int r)
{
if (p >= r)
return;
int q = p + (r - p) / 2;
mergeSort(arr, p, q);
mergeSort(arr, q + 1, r);
merge(arr, p, q, r);
}
template <typename T>
void merge(T arr[], int p, int q, int r)
{
// merge ...
}
Does this caused by a compiler specific feature?