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

Viewed 493

I use the following template function to count array items:

#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;
}

It works, but not with an empty array:

struct {} array0[] = {};
printf("%zu\n", countof(array0));

gcc 5.4 output:

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:

If I try to add a specialization:

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

it even gets weirder:

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>’

What am I doing wrong?

1 Answers
Related