0

In the following code:

template <typename T, size_t n> 
constexpr size_t array_size(T(&) [n]) { return n; }

A reference (&) is used to successfully substitute the template. Removing the reference results in this error:

'template<class T, long unsigned int n> constexpr size_t array_size(T*)'
    5 | constexpr size_t array_size(T [n]) { return n; }
note: template argument deduction/substitution failed:
note: couldn't deduce template parameter 'n'

When trying to call the function array_size with an array declared on the stack such as int test[10];.

Adding the reference seems to "force" the compiler to find the appropriate substitution. What extra information does the compiler get from the reference for it to work with the reference and fail without?

Cedric Martens
  • 1,139
  • 10
  • 23
  • Arrays decay to pointers, so `template void foo(int[n])` [is actually](https://godbolt.org/z/Kszr75Pc4) `template void foo(int*)` - `n` disappears. This is not the case for array references. – Evg Dec 27 '22 at 23:00

1 Answers1

1

A weird quirk of C++ is that you can't actually pass arrays as parameters. You can only pass pointers or references to arrays, or pointers to data. If you attempt to pass an array to a function, then it actually just passes a pointer to the data.

void foo(int array[3]) {}
void foo(int* ptr) {} //fails to compile because `foo(int*)` already exists.

:(

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158