我已阅读以下链接如何通过模板函数计算数组的大小:
- How does this “size of array” template function work? [duplicate]
- Can someone explain this template code that gives me the size of an array? [duplicate]
Magic arguments in function templates
但是这个技巧在数组为零的情况下不起作用。为什么下面的代码不正确? 例如,在线编译器 ideone 会打印以下错误消息:
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/