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;
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.