首页 > 解决方案 > 模板函数声明的顺序在 g++ 中是否重要?

问题描述

当我使用递归编写合并排序时,我按此顺序使用函数声明了mergeSort(T arr[], int n)and 内部排序。当我编译它时,MSVC 工作正常,但是 g++ 给我这样的输出:mergeSort(T arr[], int p, int r)merge(T arr[], int p, int q, int r)

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);
     ~~~~~~~~~^~~~~~~~~~~~~~~

我想原因可能是函数声明的顺序,我通过调用更改了声明顺序。这一次 g++ 也有效。我想知道的是为什么会这样?

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 ...
}

这是由编译器特定功能引起的吗?

标签: c++visual-c++g++

解决方案


推荐阅读