2

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?

  • GCC is right. MSVC is known to have trouble implementing two-phase name lookup. – L. F. Jul 03 '19 at 04:01
  • In simple cases like this, the standard rule is just the same as with non-template functions, which must be declared before use. – Davis Herring Jul 03 '19 at 04:33
  • Old versions of MSVC are bugged , [see here](https://stackoverflow.com/a/47357657/1505939) – M.M Jul 03 '19 at 04:58
  • Thanks for your answers! But in my case(declaration order shown as above) MSVC can do the compile and worked as expected while g++ gave me some error messages. I use vs 2015 and simple `cl xxx.cpp`. The version of gcc is 7.4.0 and the command I use is `g++ xxx.cpp -o xxx.out`. Could you please give me some more information? – Xu_shan_shan Jul 03 '19 at 11:37

0 Answers0