2

In this MCVE, the compiler complains that processArray can't match the parameter list (arr). The fix is to replace T elements[SIZE] with T (&elements)[SIZE]. Why do I need to do this, and under what circumstance? I wouldn't use & to pass an array into a function ordinarily. (Only reason I thought of it is that's how C++20's new version of istream& operator>> describes its char-array parameter.)

template <typename T, int SIZE>
void processArray(T elements[SIZE])
{
    for (int i = 0; i < SIZE; ++i)
        elements[i] = 2;
}

int main()
{
    int arr[3];

    processArray(arr);

    return 0;
}
Topological Sort
  • 2,733
  • 2
  • 27
  • 54

1 Answers1

5

This is because of array decay. Unless you pass an array by reference, it is going to decay into a pointer. That means

void processArray(T elements[SIZE])

is really

void processArray(T* elements)

and there is no way to get what SIZE is for your template since a pointer doesn't know the size of the array it points to.

Once you make the array parameter a reference, you stop this decaying and can get the size out of the array that is passed to the function.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402