【发布时间】:2017-02-20 04:24:37
【问题描述】:
我已阅读以下链接如何通过模板函数计算数组的大小:
- 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 打印以下错误消息:
错误:没有匹配函数调用“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);
}
【问题讨论】:
-
不在一个类中的零大小数组是非法的。
-
@NathanOliver 我可能是错的,但 iirc 0 大小的数组只允许在 C 中用于可变大小的结构。
-
只需将初始化替换为 int arr[]={} 或 int arr[0];
-
Clang++ 打印出一个解释:'候选模板被忽略:替换失败...零长度数组在 C++ 中是不允许的'。
-
@krzaq 这可能是我见过的一个扩展。至少在 OP 的情况下是非法的。