This isn't the nicest way of doing it, but since you're asking: The return type of the template function ArraySizeHelper
is char[N]
, where the argument of the function is a (reference to an) array of size N of type T
. Template argument deduction instantiates this template with the matching number N, and so sizeof(char[N])
is just N, which is what you get.
A nicer version could be written as follows. (You need C++0x for constexpr
; if you omit it, this will not be a constant expression.)
template <typename T, size_t N> constexpr size_t array_size(const T (&)[N]) { return N; }
Usage:
int x[20];
array_size(x); // == 20
Update: If you are in C++0x, here is another solution that gives a constexpr, thanks to decltype:
#include <type_traits>
template <typename T> struct array_traits;
template <typename T, unsigned int N> struct array_traits<T[N]>
{
static const unsigned int size = N;
typedef std::decay<T>::type type;
};
// Usage:
int x[20];
array_traits<decltype(x)>::size; // == 20