używam następującą funkcję szablonu policzyć elementy tablicy:Jak policzyć elementy macierzy C++ z funkcji szablonu, pozwalając jednocześnie na pustych tablic
#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;
}
To działa, ale nie z pustej tablicy:
struct {} array0[] = {};
printf("%zu\n", countof(array0));
gcc 5.4 wyjście:
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:
Gdy próbuję dodać specjalność:
template<typename T> constexpr
size_t countof(T(&)[0])
{
return 0;
}
nawet dostaje dziwniejsze:
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>’
Co robię źle?
Według tego odniesienia deklaracji [] array (http://en.cppreference.com/w/cpp/language/array) wyrażenie wielkość musi ocenić "do wartości większej od zera". W skrócie, tablice o zerowym rozmiarze są nieprawidłowe. –
Dyskusja na temat komunikatów o błędach błędnego kompilatora! –
Zamiast tego możesz użyć 'std :: array'. –