Getting the length of an array. Compiler errors.

感情迁移 提交于 2019-12-11 01:18:13

问题


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).



来源:https://stackoverflow.com/questions/18482109/getting-the-length-of-an-array-compiler-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!