我用下面的模板函數計算數組項:如何使用模板函數算C++數組項,同時允許空數組
#include <stdio.h>
template<typename T, size_t N> constexpr
size_t countof(T(&)[N])
{
return N;
}
int main(void)
{
struct {} arrayN[] = {{}, {}, {}};
printf("%zu\n", countof(arrayN));
return 0;
}
它的工作原理,但不是一個空數組:
struct {} array0[] = {};
printf("%zu\n", 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>’
我在做什麼錯?
根據[該數組聲明引用(http://en.cppreference.com/w/cpp/language/array)大小表達式的值必須「到大於零的值」。簡而言之,零大小的數組無效。 –
討論編譯器錯誤信息! –
你可以用'std :: array'代替。 –