更新时间:2022-05-07 08:47:42
首先,让我们解剖参数, T(安培)【尺寸】
。阅读声明从里面出来,从右到左,括号组第一:它的那就是大小尺寸
类型 T的数组的引用一位不愿透露姓名的参数
。
First let's dissect the parameter, T(&)[size]
. Read declarations from inside out, right to left, parenthesis group first: It's an unnamed parameter that is a reference to an array of size size
of type T
.
即,它接受的任何阵列,其中该阵列的类型和尺寸是模板参数的参考。
That is, it accepts a reference to any array, where the type and size of the array are template parameters.
如果我们把它作为这样的:
If we call it as such:
int a[10];
GetArrLength(a);
编译器将尝试推断出模板参数。对于参数类型来匹配你传递什么, T
必须 INT
和尺寸
必须是10(使参数数组引用10 INT
的)。
The compiler will try to deduce the template parameters. For the parameter type to match what you're passing, T
must be int
and size
must be 10 (making the parameter a reference to an array of 10 int
's).
您再回到该大小,让您数组中元素的个数。
You then return that size, giving you the number of elements in an array.
有两个问题这个code。首先,大小不能为负,所以它没有意义使用符号的类型作为模板参数和返回类型。相反,一个无符号的类型应该使用;***是的std ::为size_t
:
There are two "problems" with this code. Firstly, sizes cannot be negative, so it doesn't make sense to use a signed type as the template parameter and return type. Rather, an unsigned type should be used; best would be std::size_t
:
template<typename T, std::size_t Size>
std::size_t GetArrLength(T(&)[Size]) { return size; }
第二个是,这个函数的结果是不恒定的前pression,即使一个数组大小。虽然这是在大多数情况下细,它会更好,如果我们能够从它那里得到一个恒定的前pression。这就是你结束了这个解决方案:
The second is that the result of this function is not a constant-expression, even though an arrays size is. While that's fine in most situations, it would be better if we could get a constant-expression from it. That's where you end up with this solution:
template <std::size_t N>
struct type_of_size
{
typedef char type[N];
};
template <typename T, std::size_t Size>
typename type_of_size<Size>::type& sizeof_array_helper(T(&)[Size]);
#define sizeof_array(pArray) sizeof(sizeof_array_helper(pArray))
这被用作这样的:
int a[10];
const std::size_t n = sizeof_array(a); // constant-expression!
它的工作原理是三件事情:第一是同样的想法如上所示,模板参数将被填掉给你数组的大小
It works by three things: the first is the same idea as above, that template parameters will be filled out giving you the array's size.
第二部分是利用这些信息,使具有特定尺寸的类型,因此 type_of_size
帮手。这部分是不是绝对必要的,但我觉得它使code更容易阅读。 A 的char [N]
的大小等于 N
,一如既往,因此我们可以滥用,为存储的在一个类型本身!
The second part is using that information to make a type with a specific size, hence the type_of_size
helper. That part isn't strictly necessary, but I think it makes the code easier to read. A char[N]
has a size equal to N
, always, hence we can abuse that to "store" the size of the array...in the size of a type itself!
第三部分是让与这种规模的sizeof
。它实际上并没有什么评价,所以我们不需要为函数的定义。它只是说如果你做到这一点...规模将是...。而且规模是我们的存储的大小,字符
阵列
The third part is getting that size with sizeof
. It doesn't actually evaluate anything, so we don't need a definition for the function. It simply says "If you were to do this...the size would be...". And the size is our "stored" size, in the char
array.