有人可以解释这个模板code,它给了我一个数组的大小? [英] Can someone explain this template code that gives me the size of an array?

查看:110
本文介绍了有人可以解释这个模板code,它给了我一个数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

与我们调用previously定义的数组 A 将隐式实例如下功能:

size_t array_size(const int (&)[3]) {
    return 3;
}

这可以用这样的:

Which can be used like this:

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 和元素类型字符。现在,你可以得到传递的数组的编译时确定的尺寸:

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 元素的数组有sizeof的 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.

这篇关于有人可以解释这个模板code,它给了我一个数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆