Does that actually compile? It looks like they are missing some parts...anyway, this is what I think they tried to do:
1 2 3 4 5 6 7 8 9 10 11
template <typename T,unsigned S>
inlineunsigned //returns the size
arraysize(const T (&v)[S]) { //basically, take a static array of any type T
//with a number of elements S; dynamic arrays don't work
return S;
}
int main() {
int a[10];
std::cout<<arraysize(a)<<std::endl;
}
Ok, it seems like a more convoluted way than what I posted.
I have no idea how that works (>_>), but in the end it returns a static char array, with N elements (the number of elements in the array you passed). Since each char is one byte, taking the sizeof this char array will give you the number of elements in it.
Honestly, it basically just as bad as sizeof(array/array[0])...except they are assuming array[0] is 1 in their case.
The sizeof operator when applied to a function gives the sizeof the function's return type.
So for example if you have the function declaration int somefunction();
then the sizeof(somefunction) will be same as sizeof (int).
Note that we don't need to give the function a body in order to use the sizeof operator on it.
(You need the body if you want to call the function - which we are not going to do).
The function declaration char(&array(T(&)[N]))[N]; means a function taking a reference to an array of type T of number of elements N and returning a reference to an array of type char of number of elements N.
So the sizeof this function would be sizeof (char[N])
So in your code if you do the relevant template parameter substitution - we will have: char(&array( int(&)[10]))[10];
So you see that the sizeof the function return type is sizeof char[10] which is 10 (as a char is 1 byte).
**HERE IS AN IMPORTANT BIT**
That particular code gives the NUMBER OF ELEMENTS in the original array!!!
If you want the actual size in bytes of the original array - you would do: char(& array(T(&)[N]) ) [N*sizeof(T)];