3 Answers
3

but I can't wrap my head around the syntax. Especially the T (&) [size] part...

That part is a reference to an array. There is the "right-left rule" for deciphering any C and C++
declarations.

Because function templates deduce template argument types from the supplied function arguments what this function template does is deduce the type and element count of an array and return the count.

Functions can't accept array types by value, rather only by pointer or reference. The reference is used to avoid the implicit conversion of an array to the pointer to its first element (aka, array decay):

Array decay destroys the original type of the array and hence the size of it gets lost.

Note, that because it is a function call in C++03 the return value is not a compile time constant (i.e. the return value can't be used as a template argument). In C++11 the function can be marked with constexpr to return a compile time constant:

In the above it declares a function template with the same reference-to-an-array argument, but with the return value type of char(&)[size] (this is where the "right-left rule" can be appreciated). Note that the function call never happens at run-time, this is why the definition of function template siz is unnecessary. sizeof siz(x) is basically saying "what would be the size of the return value if siz(x) were called".

The old C/C++ way of getting the element count of an array as a compile time constant is:

@JasonS - the parens are required to avoid looking like an array of references to T
–
Flexo♦Nov 1 '11 at 13:38

ah, ok... and (T&)[size] won't work either? (sorry, don't have a C compiler up and running)
–
Jason SNov 1 '11 at 14:10

1

@JasonS No, that's the same as just T&. The parenthesis make it clear that the & doesn't refer to the type the elements of the array are made from. (A C compiler wouldn't do much good for testing it out though - there's no references in C!)
–
Flexo♦Nov 1 '11 at 14:15

1

@awoodland: AH! The light finally went on. so reference to array of T rather than array of references.
–
Jason SNov 2 '11 at 17:04