Possible Duplicate:
Can someone explain this template code that gives me the size of an array?
template <typename T,unsigned S>
unsigned ArraySize(const T (&v)[S])
{
return S;
}
I understand the T and S, but my question is why do we have to declare v as a reference variable? Or maybe I’m misunderstanding this whole thing.
I appreciate the help!
The function accepts an array by reference, and because of this, type of element
Tand sizeSis deduced by the compiler. So it returnsSwhich 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: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:See error : http://ideone.com/4mdJE
So a better implementation would be this:
Now this is perfectly fine:
See ok : http://ideone.com/Zt3UY