问题描述
我想知道在下面的代码中,编译器如何从 T(& arr)[arrsize]
函数参数推导 arrsize
模板参数.例如,当我将4元素的数组传递给它时,在函数调用中未提及数字4时,它正确地将 arrsize
参数确定为4.但是,如果我传递该数组通常(不作为对数组的引用),也就是说,如果我将 T(& arr)[arrsize]
更改为 T arr [arrsize]
,在模板参数列表中显式提供 arrsize
参数.
I am wondering how, in the following piece of code, the compiler deduces the arrsize
template argument from the T (&arr)[arrsize]
function argument. For example, when I pass a 4-element array to it, without mentioning the number 4 in my call to the function, it correctly determines the arrsize
argument to be 4. However, if I pass the array normally (not as a reference to array), that is, if I change T (&arr)[arrsize]
to T arr[arrsize]
, it requires me to explicitly provide the arrsize
argument in the template argument list.
template <class T, int arrsize> void bubblesort(T (&arr)[arrsize], int order=1)
{
if (order==0) return;
bool ascending = (order>0);
int i,j;
for (i=arrsize; i>0; i--)
for (j=0; j<i-1; j++)
if (ascending?(arr[j]>arr[j+1]):(arr[j]<arr[j+1])) swap(arr[j],arr[j+1]);
}
所以我的问题是:
-
当我向函数传递对数组的引用时,编译器如何自动找出
arrsize
参数的值?(机制是什么?)
How does the compiler figure out the value of the
arrsize
argument automatically when I pass to the function a reference to an array? (What is the mechanism?)
如果我正常传递数组,为什么编译器不能做同样的事情?(通常是指不使用参考符号)
Why can the compiler not do the same if I pass the array normally? (by normally I mean without using the reference symbol)
推荐答案
- 它可以推断出大小,因为该大小在编译时在调用上下文中是已知的.如果您具有
int a [4]
,并且编写了bubblesort(a)
,则编译器将使用a
的类型为int [4]
可以将arrsize
推导出为4.如果您尝试在p
满足以下条件时执行bubblesort(p)
键入int *
,推导将失败,并会导致编译错误. - 如果将
T arr [arrsize]
而不是T(& arr)[arrsize]
用作参数,则编译器将自动将声明重写为T * arr
.由于arrsize
不再出现在签名中,因此无法推论得出.
- It can deduce the size because the size is known at compile-time within the calling context. If you have
int a[4]
, and you writebubblesort(a)
, then the compiler uses the fact that the type ofa
isint[4]
to deducearrsize
as 4. If you try to dobubblesort(p)
whenp
has typeint*
, deduction will fail and a compile error will result. - If you write
T arr[arrsize]
as the parameter instead ofT (&arr)[arrsize]
, then the compiler will automatically rewrite the declaration asT* arr
. Sincearrsize
no longer occurs in the signature, it can't be deduced.
这篇关于当定义为模板参数时,编译器如何推断数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!