使用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"。
为什么我会收到这个警告,在没有警告的情况下计算数组大小的正确方法是什么?
这是部分答案。
首先,CCD_ 2是int&而不是int。只需记住,您可以为其赋值,并在my_array[0]
处更改值。
其次,您的代码无论如何都应该是正确的,因为对于sizeof
应用于引用类型时,结果是引用类型的大小。--cpprreference。
现在我不确定clang报告警告的原因。它可能只是识别T和T&作为传递给两个CCD_ 5运算符的完全不同的类型,并且它们对于公共CCD_。
您是否尝试过在decltype前面使用std::remove_reference_t来删除警告?或者只是按照评论中的建议删除decltype?
更新对于一些C++样式点,您也可以完全降低模式的大小,并使用元编程技术
template<typename T, size_t N>
constexpr size_t size_of_array( T (&_arr)[N]) {
return N;
}
您可以将其用作size_of_array(my_array)
。