请解释以下返回数组大小的函数
可能的重复:
有人可以解释一下吗给我数组大小的模板代码?
template <typename T,unsigned S>
unsigned ArraySize(const T (&v)[S])
{
return S;
}
我理解 T
和 S
,但我的问题是为什么我们有 将 v
声明为引用 多变的?或者也许我误解了整件事。
我很感激你的帮助!
Possible Duplicate:
Can someone explain this template code that gives me the size of an array?
template <typename T,unsigned S>
unsigned ArraySize(const T (&v)[S])
{
return S;
}
I understand the T
and S
, but my question is why do we have to declare v
as a reference variable? Or maybe I'm misunderstanding this whole thing.
I appreciate the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该函数通过引用接受数组,因此,编译器会推导出元素类型 T 和大小 S 。所以它返回
S
,它只不过是数组的大小。如果没有引用,它将退化为指针类型。所以它们之间没有区别:都是完全相同的。您可以将任意大小的数组传递给所有这些函数。
回到
ArraySize
,该函数的返回值不能用作常量表达式:参见错误:http ://ideone.com/4mdJE
因此,更好的实现是这样的:
现在这完全没问题:
请参阅 ok : http://ideone.com/Zt3UY
The function accepts an array by reference, and because of this, type of element
T
and sizeS
is deduced by the compiler. So it returnsS
which is nothing but the size of the array. In the absence of reference, it would decay into a pointer type. So there is no difference between these:All are exactly same. You can pass array of any size to all of these functions.
Coming back to
ArraySize
, the returned value of this function cannot be used as constant expression:See error : http://ideone.com/4mdJE
So a better implementation would be this:
Now this is perfectly fine:
See ok : http://ideone.com/Zt3UY
如果 v 不是引用,那么您将得到以下结果:
但是在这种情况下使用 [] 只是另一种编写方式
,不会为您提供任何大小信息。
If v wasn't a reference, then you would have this:
But the use of [] in this context is just another way of writing
which would give you no size information.