Getting the length of an array. Compiler errors.

2019-07-18 04:11发布

问题:

I've tried:

template <typename T,unsigned S> 
unsigned getArraySize(const T (&v)[S]) { return S; } 

after Motti's answer https://stackoverflow.com/a/18078435/512225

but I've got this message:

error C2265: '' : reference to a zero-sized array is illegal

What's wrong with my compiler?

I gave a look at this page: http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/4b78bcef-4c33-42f1-a4c5-fb6f702ced0b/vs6-c-compile-error-using-getaddrinfo so I tried this solution:

template <typename T,unsigned S> 
unsigned getArraySize(const T v[S]) { return S; } 

this compiles, but when I try to use it:

double myX[2] = {7,3};
std::cout << getArraySize(myX) << std::endl; 

I get a compilation error:
error C2783: 'unsigned int __cdecl getArraySize(const T [])' : could not deduce template argument for 'S'

Beside changing the compiler, is there a workaround I can use to get the array's size?

回答1:

This could be a limitation of VC6, have you tried other compilers?



回答2:

but I've got this message:

error C2265: '' : reference to a zero-sized array is illegal

Arrays with zero size are illegal in C++.
So this probably means you tried with an array of zero size.

this compiles, but when I try to use it:

If you don't use it. Then the compiler is going to ignore a template (even if it has errors). This is because you can not always deduce if a template function is correct without knowing the types involved. So unless there is a call to a template function no error message will be generated.

template <typename T,unsigned S>
unsigned getArraySize(const T v[S]) { return S; }

This fails because you are not allowed to pass arrays as parameters (you can only pass references to arrays).