如何使用模板函数对数组项进行计数C++同时允许空数组

How to count C++ array items with a template function while allowing for empty arrays

本文关键字:数组 C++ 许空 何使用 函数      更新时间:2023-10-16

我使用以下模板函数来计算数组项:

#include <stdio.h>
template<typename T, size_t N> constexpr
size_t countof(T(&)[N])
{
return N;
}
int main(void)
{
struct {} arrayN[] = {{}, {}, {}};
printf("%zun", countof(arrayN));
return 0;
}

它有效,但不适用于空数组:

struct {} array0[] = {};
printf("%zun", countof(array0));

GCC 5.4 输出:

error: no matching function for call to ‘countof(main()::<anonymous struct> [0])’
note: candidate: template<class T, long unsigned int N> constexpr size_t countof(T (&)[N])
note:   template argument deduction/substitution failed:

如果我尝试添加专业化:

template<typename T> constexpr
size_t countof(T(&)[0])
{
return 0;
}

它甚至变得更奇怪:

error: no matching function for call to ‘countof(main()::<anonymous struct> [0])’
note: candidate: template<class T, long unsigned int N> constexpr size_t countof(T (&)[N])
note:   template argument deduction/substitution failed:
note: candidate: template<class T> constexpr size_t countof(T (&)[0])
note:   template argument deduction/substitution failed:
note:   template argument ‘-1’ does not match ‘#‘integer_cst’ not supported by dump_decl#<declaration error>’

我做错了什么?

根据 2011 年标准第 8.5.1 节,"空的初始值设定项列表 {} 不应用作未知边界数组的初始值设定项子句",并注意:"语法提供了空的初始值设定项列表,但C++没有零长度数组"。

现在我想知道为什么声明会被编译......