【发布时间】:2021-04-05 02:40:17
【问题描述】:
使用 Apple Clang 12.0.0 编译此代码:
int my_array[10];
int arr_size = sizeof(my_array) / sizeof(decltype(my_array[0]));
并收到此警告/错误:
Expression does not compute the number of elements in this array; element type is 'int', not 'decltype(my_array[0])' (aka 'int &')
注意,这是简化的代码。在实际代码中,有一个类类型而不是 'int',而不是 '10' 有一个表达式。
为什么我会收到此警告,在没有警告的情况下计算数组大小的正确方法是什么?
【问题讨论】:
-
警告在我看来是错误的:
decltype(my_array[0])实际上应该是int而不是int&。解决方法很简单——只需删除decltype,改成sizeof(my_array[0])。或使用std::extent<decltype(my_array)>::value -
这留下了为什么警告的问题?
-
关于C++的问题请加c++标签,让更多用户看到。
标签: c++ arrays c++11 warnings clang++