• Post author:
  • Post category:IT
  • Post comments:0评论


template<typename T, size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N];
#define arraysize(array) (sizeof(ArraySizeHelper(array)))C++11版本 :template<typename T, size_t N>auto ArraySizeHelper(T (&array)[N]) -> char(&)[N];


The function template is namedArraySizeHelper, for a function that takes one argument, a reference to aT [N], and returns a reference to achar [N].

The macro passes your object (let's say it'sX obj[M]) as the argument. The compiler infers thatT == XandN == M. So it declares a function with a return type ofchar (&)[M]. The macro then wraps this return value withsizeof, so it's really doingsizeof(char [M]), which isM.

If you give it a non-array type (e.g. aT *), then the template parameter inference will fail.

As @Alf points out below, the advantage of this hybrid template-macro system over the alternative template-only approach is that this gives you a compile-time constant.