c++ - 为什么编译器在数组为零的情况下不推导出模板参数?

标签 c++ arrays templates size

我已阅读以下链接如何通过模板函数计算数组的大小:

error: no matching function for call to 'size_of_array(int [0])'
std::size_t num = size_of_array(arr);

#include <cstddef>
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
   return N;
}
int main()
{
  int arr[0]={};
  std::size_t num = size_of_array(arr);
}

最佳答案

来自标准草案 n4296,§8.3.4 数组:

In a declaration T D where D has the form

D1 [ constant-expression ] attribute-specifier-seq

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type;

...

If the constant-expression is present, it shall be a converted constant expression of type std::size_t and its value shall be greater than zero.

所以您的代码无效。

关于c++ - 为什么编译器在数组为零的情况下不推导出模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980445/

相关文章:

c++ - 查找存储在优先级队列中的值的有效方法

c++ - 找出在 Visual Studio 2012 中的 C++ 项目中从未调用过哪些代码

c++ - 即使在使用守卫后也不能使用在另一个类中定义的结构

javascript - Array 对象与 Object 是否不同(认为两者的 typeof 返回相同的值)?

c++ - 为什么 std::function 不是有效的模板参数,而函数指针是?

c++ - 为什么用作嵌套成员的非模板类是不完整类型?

c++ - 如何找到数组左侧和右侧的最大元素?

c++ - 使用数组查找 HCF,得到未知输出 (C++)

java - 当长度不同时按大小并排打印 2 个数组

C++ 类重载 : is it possible to make compiler see which one to use based on template?