如何" sizeof的"在这个辅助工作,确定数组的大小? [英] How does "sizeof" work in this helper for determining array size?

查看:155
本文介绍了如何" sizeof的"在这个辅助工作,确定数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这篇文章这带来了以下模板,并获取数组大小的宏:

 模板< typename的类型,为size_t尺寸和GT;
CHAR(安培; ArraySizeHelper(类型(安培;阵列)[尺寸]))【尺寸】;
#定义_countof(阵列)的sizeof(ArraySizeHelper(阵列))

和我发现下面的部分完全不清楚。 的sizeof 应用到函数声明。我期望得到的结果是函数指针的大小。为什么会获得返回值的大小呢?


解决方案

 模板< typename的类型,为size_t尺寸和GT;
CHAR(安培; ArraySizeHelper(类型(安培;阵列)[尺寸]))【尺寸】;
#定义_countof(阵列)的sizeof(ArraySizeHelper(阵列))


  

的sizeof 应用到函数声明。我期望得到的结果是函数指针的大小。为什么会获得返回值的大小呢?


这不是的sizeof ArraySizeHelper (这将是非法的 - 不能把的sizeof 函数),也不的sizeof和放大器; ArraySizeHelper - 甚至没有暗示从函数指针到函数隐式转换的标准是明令禁止的,对于C ++ 0x中见5.3.3)。相反,它是的sizeof ArraySizeHelper(阵列)相当于的sizeof 的值,函数调用返回时,即的sizeof的char [尺寸] 因此,尺寸

I've found this article that brings up the following template and a macro for getting array size:

template<typename Type, size_t Size>
char ( &ArraySizeHelper(Type( &Array )[Size]) )[Size];
#define _countof(Array) sizeof(ArraySizeHelper(Array))

and I find the following part totally unclear. sizeof is applied to a function declaration. I'd expect the result to be "size of function pointer". Why does it obtain "size of return value" instead?

解决方案

template<typename Type, size_t Size>
char (&ArraySizeHelper(Type(&Array)[Size]))[Size];
#define _countof(Array) sizeof(ArraySizeHelper(Array))

sizeof is applied to a function declaration. I'd expect the result to be "size of function pointer". Why does it obtain "size of return value" instead?

It's not sizeof ArraySizeHelper (which would be illegal - can't take sizeof a function), nor sizeof &ArraySizeHelper - not even implicitly as implicit conversion from function to pointer-to-function is explicitly disallowed by the Standard, for C++0x see 5.3.3). Rather, it's sizeof ArraySizeHelper(Array) which is equivalent to sizeof the value that the function call returns, i.e. sizeof char[Size] hence Size.

这篇关于如何&QUOT; sizeof的&QUOT;在这个辅助工作,确定数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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