I come across the following code, which returns the size of a C style array.
template <typename Type, int N>
int GetArraySize(Type (&array)[N])
{
(void) sizeof (0[array]);
return N;
}
The templated part seems to have been already explained in this question.
But still, I don't understand what is the utility of the sizeof
line. Any ideas?
Some suggest that it is to avoid unused variable warning, but a simpler #pragma
could have been used, right?
Moreover, will this piece of code be effective in any situation? Aren't there any restrictions?
#pragma
is not standard (although most mainstream compilers do implement it), but casting to void is0[array]
is the same asarray[0]
array
parameter name could be omitted to avoid unused variable warning. Also it should use and returnsize_t
.