The best explanation why your solution does not work is in Maroun's answer.
About the second part of the question ("how can it be done?"), you can do this with a template function:
template const size_t size(const T (&)[n]) { return n; }
Of course, this works only if the size of the array is constant (constant, as seen by the compiler), but it can only ever work in this case anyway -- an array does not store its size anywhere, so if it's not a known compile-time constant, there is no way to know it.
If you need this to work with arrays that are not compile-time constants (say, something you allocate with operator new[]
, or using a non-standard compiler extension), you need to explicitly store the size somewhere.
(Incidentially, my above statement is technically wrong, indeed the allocation size is usually stored, but this is an implementation detail which you cannot and should not depend on.)