为什么我们需要一个模板来计算数组的大小,为什么我不能直接使用诸如int这样的预定义数据类型进行计算
我看过这样的代码
template<typename T,int SIZE>
size_t array_size(const T (&array)[SIZE])
{
return SIZE;
}
Run Code Online (Sandbox Code Playgroud)
如果我们直接使用int而不是模板,为什么会抛出错误
int N;
int size(int (&arr1)[N]) //Passing the array by reference
{
return N; //Correctly returns the size too [cool trick ;-)]
}
Run Code Online (Sandbox Code Playgroud)
它如何计算大小
数组的大小是其类型的一部分。当你创建一个数组像
int array[5]{};
Run Code Online (Sandbox Code Playgroud)
那么它的类型实际上是int[5],不是int[]或int*。这意味着当你做
template<typename T,int SIZE>
size_t array_size(const T (&array)[SIZE])
{
return SIZE;
}
Run Code Online (Sandbox Code Playgroud)
例如array,您传递时,编译器将推论出T和SIZE,int[5]而您分别获得int和5。
int N;
int size(int (&arr1)[N]) //Passing the array by reference
{
return N; //Correctly returns the size too [cool trick ;-)]
}
Run Code Online (Sandbox Code Playgroud)
另一方面,不会做同样的事情。这声明了一个采用size数组的函数N,但是由于N它不是常量表达式,因此甚至无法编译。即使您具有非标准扩展名(例如gcc的VLA扩展名),N也永远不会更改,并且代码仍无法编译。即使要编译,N也不会更改,因此无论传递什么大小的数组,该函数始终会返回相同的结果。
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |