且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当定义为模板参数时,编译器如何推断数组大小?

更新时间:2023-11-10 19:52:10

  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.