c++ - 模板函数声明的顺序在 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 ...
}
这是由编译器特定功能引起的吗?
解决方案
推荐阅读
- java - 为什么即使我将元素推入堆栈,堆栈仍然是空的
- javascript - Getting Attribute from option form in Java script
- mysql - 仅在满足某些约束时如何将行添加到数据库
- r - SelectInput 更改 Shiny 中的多个元素
- node.js - node js应用内存分析工具
- c# - 将文件夹名称连接到文件名并将文件复制到文件夹
- php - 允许在 WooCommerce 的时间范围内购买特定产品
- c - 字符串文字如何在 c 中工作(尤其是宽字符串 - L“some string”)?
- android - 如何从 NotificationListenerService 获取 Uri?
- python-3.x - 我的 tk 脚本在我直接运行时有效(python 启动器在 root.quit 上退出)但在导入另一个脚本时不起作用(python 启动器冻结)