以下代码返回堆栈分配的数组的大小:
template<typename T, int size>
int siz(T (&) [size])
{
return size;
}
Run Code Online (Sandbox Code Playgroud)
但我无法理解语法.特别是T (&) [size]部分......
在Google V8项目中读取globals.h时遇到以下宏定义.
// The expression ARRAY_SIZE(a) is a compile-time constant of type
// size_t which represents the number of elements of the given
// array. You should only use ARRAY_SIZE on statically allocated
// arrays.
#define ARRAY_SIZE(a) \
((sizeof(a) / sizeof(*(a))) / \
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
Run Code Online (Sandbox Code Playgroud)
我的问题是后半部分:static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))).我想到的一件事是:由于后一部分将始终求1值为(类型)size_t,整个表达式将被提升为size_t.
如果这个假设是正确的,那么还有另一个问题:由于sizeof运算符的返回类型是size_t,为什么需要这样的推广?以这种方式定义宏有什么好处?
template <typename _CountofType, size_t _SizeOfArray>
char( *__countof_helper1( _CountofType(&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _myCountOf(_Array) (sizeof(*__countof_helper1(_Array)) + 0)
Run Code Online (Sandbox Code Playgroud)
我试图理解 _countof 宏,但无法理解它如何能够计算数组的大小。请有人一点一点解释上面的代码