Mysterious oneliner template template, anyone?

I read this page: C ++ Tip: how to get the length of an array . The writer introduced a code snippet to find out the size of static arrays.

template<typename T, int size> int GetArrLength(T(&)[size]){return size;} // what does '(&)' mean ? . . . int arr[17]; int arrSize = GetArrLength(arr); // arrSize = 17 

Can anyone shed some light on this code because I could not understand how this works.

+4
source share
4 answers

The function is passed by reference ( & ) to an array of type T and size size .

+7
source

SizeOf (x) / SizeOf (x [0])

It will not catch errors if the array degrades to a pointer type, but it will still compile!

The floating point option is bulletproof.

+1
source

T (&) [size] refers to T [size]. If you do not use the link, C ++ will treat T [size] as T *, and the default of the function template parameter will not work.

+1
source

Wow, this is complicated. I don't know either, but if you keep reading the comments on this page:

substantially

int arr [17]; int arrSize = GetArrLength (arr);

which creates this function:

int GetArrLength (int (&) [17]) {return 17;}

So, and this should mean a link, as it always happens, so it takes a reference to the type of array and size (the second element in the template), and then the size of the incoming array.

I think that I will stick to the old

 sizeof(x)/sizeof(x[0]) 
0
source

All Articles