【问题标题】:Understanding "Expression does not compute the number of elements in this array"了解“表达式不计算此数组中的元素数”
【发布时间】: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++


【解决方案1】:

这是部分答案。

首先,decltype(my_array[0]) 的类型是 int& 而不是 int,这并不奇怪。请记住,您可以分配给它并更改 my_array[0] 的值。

其次,你的代码应该是正确的,因为sizeof

当应用于引用类型时,结果是被引用类型的大小。 --cppreference.

现在我不确定为什么 clang 会报告警告。可能只是它将 T 和 T& 识别为传递给两个 sizeof 运算符的完全不同的类型,并且它们对于常见的 sizeof(my_array)/sizeof(my_array[0]) 模式有某种例外。

您是否尝试在 decltype 前面使用 std::remove_reference_t 来删除警告?或者只是按照 cmets 中的建议删除 decltype?

更新 对于某些 C++ 样式点,您还可以完全放弃 sizeof 模式并使用元编程技术

template<typename T, size_t N>
size_t size_of_array( T (&_arr)[N]) {
   return N;
}

您可以将其用作size_of_array(my_array)

【讨论】:

  • 我删除了decltype
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多