当定义为模板参数时,编译器如何推断数组大小? [英] How does the compiler deduce array size when defined as a template parameter?

查看:55
本文介绍了当定义为模板参数时,编译器如何推断数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在下面的代码中,编译器如何从 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]);
}

所以我的问题是:

  1. 当我向函数传递对数组的引用时,编译器如何自动找出 arrsize 参数的值?(机制是什么?)

  1. 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)

推荐答案

  1. 它可以推断出大小,因为该大小在编译时在调用上下文中是已知的.如果您具有 int a [4] ,并且编写了 bubblesort(a),则编译器将使用 a 的类型为 int [4] 可以将 arrsize 推导出为4.如果您尝试在 p 满足以下条件时执行 bubblesort(p)键入 int * ,推导将失败,并会导致编译错误.
  2. 如果将 T arr [arrsize] 而不是 T(& arr)[arrsize] 用作参数,则编译器将自动将声明重写为 T * arr .由于 arrsize 不再出现在签名中,因此无法推论得出.
  1. 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 write bubblesort(a), then the compiler uses the fact that the type of a is int[4] to deduce arrsize as 4. If you try to do bubblesort(p) when p has type int*, deduction will fail and a compile error will result.
  2. If you write T arr[arrsize] as the parameter instead of T (&arr)[arrsize], then the compiler will automatically rewrite the declaration as T* arr. Since arrsize no longer occurs in the signature, it can't be deduced.

这篇关于当定义为模板参数时,编译器如何推断数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆