Reputation: 545
I have read the following links how to calculate size of an array through template function:
Magic arguments in function templates
But this trick doesn't work in case of zero array. Why is the following code not correct? For instance the online compiler ideone prints the following error message:
error: no matching function for call to 'size_of_array(int [0])'
std::size_t num = size_of_array(arr);
#include <cstddef>
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
return N;
}
int main()
{
int arr[0]={};
std::size_t num = size_of_array(arr);
}
Upvotes: 2
Views: 159
Reputation: 50568
According with [temp.deduct/8] (working draft, template argument deduction, emphasis mine):
Type deduction may fail for the following reasons:
[...]
- Attempting to create an array with an element type that is void, a function type, a reference type, or an abstract class type, or attempting to create an array with a size that is zero or negative
Type deduction for zero-length arrays may fail (mainly because zero-length arrays are not allowed as well) and that's why you get an error.
Note also that from the same paragraph we have the following (emphasis mine)
An invalid type or expression is one that would be ill-formed, with a diagnostic required, if written using the substituted arguments.
Upvotes: 2
Reputation: 17483
From the standard draft n4296, §8.3.4 Arrays:
In a declaration T D where D has the form
D1 [ constant-expression ] attribute-specifier-seq
and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type;
...
If the constant-expression is present, it shall be a converted constant expression of type std::size_t and its value shall be greater than zero.
So your code is not valid.
Upvotes: 2