gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:56:18 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com