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?
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.
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).
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]);
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With