问题描述
template<typename T, size_t n>
size_t array_size(const T (&)[n])
{
return n;
}
我没有得到的部分是这个模板函数的参数.当我将数组传递给 n
作为数组中元素的数量时,它会发生什么?
The part that I don't get is the parameters for this template function. What happens with the array when I pass it through there that gives n
as the number of elements in the array?
推荐答案
嗯,首先你必须明白,试图从数组中获取一个值可以给你一个指向它的第一个元素的指针:
Well, first you have to understand that trying to get a value out of an array can give you a pointer to its first element:
int a[] = {1, 2, 3};
int *ap = a; // a pointer, size is lost
int (&ar)[3] = a; // a reference to the array, size is not lost
引用引用使用其确切类型或基类类型的对象.关键是模板通过引用获取数组.数组(不是对它们的引用)作为参数在 C++ 中不存在.如果你给一个参数一个数组类型,它将是一个指针.所以当我们想知道传递的数组的大小时,使用引用是必要的.大小和元素类型是自动推导出来的,就像函数模板的情况一样.以下模板
References refer to objects using their exact type or their base-class type. The key is that the template takes arrays by reference. Arrays (not references to them) as parameters do not exist in C++. If you give a parameter an array type, it will be a pointer instead. So using a reference is necessary when we want to know the size of the passed array. The size and the element type are automatically deduced, as is generally the case for function templates. The following template
template<typename T, size_t n>
size_t array_size(const T (&)[n]) {
return n;
}
使用我们之前定义的数组 a
调用将隐式实例化以下函数:
Called with our previously defined array a
will implicitly instantiate the following function:
size_t array_size(const int (&)[3]) {
return 3;
}
可以这样使用:
size_t size_of_a = array_size(a);
我前段时间做了一个变体 可以在编译时确定一个值.它不是直接返回值,而是根据 n
为模板提供返回类型:
There's a variation I made up some time ago which can determine a value at compile time. Instead of returning the value directly, it gives the template a return type depending on n
:
template<typename T, size_t n>
char (& array_size(const T (&)[n]) )[n];
你说如果数组有 n
个元素,返回类型是一个对大小为 n
和元素类型为 char
的数组的引用.现在,您可以获得传递数组的编译时确定的大小:
You say if the array has n
elements, the return type is a reference to an array having size n
and element type char
. Now, you can get a compile-time determined size of the passed array:
size_t size_of_a = sizeof(array_size(a));
因为具有 n
个元素的 char
数组的大小为 n
,这也将为您提供给定数组中的元素数.在编译时,你可以这样做
Because an array of char
having n
elements has sizeof n
, that will give you the number of elements in the given array too. At compile time, so you can do
int havingSameSize[sizeof(array_size(a))];
因为函数从来没有被真正调用过,所以不需要定义,所以它没有主体.希望我能把事情弄清楚一点.
Because the function never is actually called, it doesn't need to be defined, so it doesn't have a body. Hope I could clear the matter up a little bit.
这篇关于有人可以解释这个给我数组大小的模板代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!