Use C++ template to know the length of C-style array, we need this:
#include<stdio.h>
template<class T,size_t N>
size_t length(T (&a)[N]){ return N; }
int main() {
int fd[2];
printf("%lld\n", length(fd));;
return 0;
}
It works, prints 2. My question is about the syntax.
In the declaration of length, why the parameter should be like (&a)[N], and a[N] doesn't work?
If I change to
template<class T,size_t N>
size_t length(T a[N]){ return N; }
gcc will say:
template argument deduction/substitution failed:
couldn't deduce template parameter 'N'
Why need an extra & and a pair of braces around array identifier here, what's the template rule / syntax rule behind this?
Appreciate detailed explanations.