The function accepts an array by reference, and because of this, type of element T
and size S
is deduced by the compiler. So it returns S
which is nothing but the size of the array. In the absence of reference, it would decay into a pointer type. So there is no difference between these:
void f(int v[100]); //declaration of f
void f(int v[200]); //redeclaration of f
void f(int v[]); //redeclaration of f
void f(int *v); //redeclaration of f
All are exactly same. You can pass array of any size to all of these functions.
Coming back to ArraySize
, the returned value of this function cannot be used as constant expression:
int a[10];
SomeClassTemplate<ArraySize(a)> obj; //error
See error : http://ideone.com/4mdJE
So a better implementation would be this:
template <typename T,unsigned S>
char (&ArraySizeHelper(const T (&v)[S]))[S]; //no need to define it!
#define ArraySize(a) sizeof(ArraySizeHelper(a))
Now this is perfectly fine:
int a[10];
SomeClassTemplate<ArraySize(a)> obj; //ok
See ok : http://ideone.com/Zt3UY