2

I have read the following links how to calculate size of an array through template function:

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);
}
Community
  • 1
  • 1
mhd
  • 535
  • 1
  • 5
  • 12

2 Answers2

2

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.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • I suspect the relevant part is the one about type deduction that mentions this one. – skypjack Oct 11 '16 at 17:18
  • @skypjack yeap, you're right and your answer reflects the essence of the question better, +1 from me. Nevertheless it's worth to mention that the program isn't correct because of zero-sized array usage. – Edgar Rokjān Oct 11 '16 at 17:27
2

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.

skypjack
  • 49,335
  • 19
  • 95
  • 187
  • Thank you. I have checked out this code with gcc for 98, 03, 11, 14 standards. But it did not show the error message about of definition of a zero sized array. So gcc does not implement this feature. – mhd Oct 11 '16 at 20:57
  • @mhd I didn't get your comment, sorry. What feature GCC doesn't implement? You got an error out of your code and I've given you an idea about the reason. – skypjack Oct 13 '16 at 16:18
  • In my comment above I meant the zero sized array which is a not correct code. I compiled this code `int main(){int arr[0]={};}` with gcc v6.2.1 with following options: -std=c++98; -std=c++03; -std=c++11; -std=c++14; But gcc didn't print an error message about the zero sized array. – mhd Oct 17 '16 at 16:38
  • 1
    @mhd Use option `-pedantic`. It compiles because of a compiler extension, but with that option it warns you saying that it's not valid code. – skypjack Oct 17 '16 at 16:45