How does the compiler deduce array size when defined as a template parameter?

随声附和 提交于 2020-01-06 15:19:47

问题


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]);
}

So my question is:

  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?)

  2. Why can the compiler not do the same if I pass the array normally? (by normally I mean without using the reference symbol)


回答1:


  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.



回答2:


T arr[arrsize] as a formal argument decays to just T* arr, where the arrsize is ignored completely (as indeed is the array nature of that argument).



来源:https://stackoverflow.com/questions/37952603/how-does-the-compiler-deduce-array-size-when-defined-as-a-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!