Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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?

like image 901
airman Avatar asked Aug 04 '17 08:08

airman


People also ask

How do you count the number of elements in an array in C++?

Using sort function() Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements.

Can an array have size 0 C++?

Zero-length array declarations are not allowed, even though some compilers offer them as extensions (typically as a pre-C99 implementation of flexible array members).

How do I get the size of an array in CPP?

In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


1 Answers

According to section 8.5.1 of the 2011 standard, "An empty initializer list {} shall not be used as the initializer-clause for an array of unknown bound", with the note: "The syntax provides for empty initializer-lists, but nonetheless C ++ does not have zero length arrays".

Now I wonder why the declaration gets compiled...

like image 142
airman Avatar answered Nov 15 '22 04:11

airman