In a parameter list T arr[]
is the same T* arr
, so arr
is a pointer. The only way to pass an array to a function is by reference. To declare an array reference you'd write T (&arr)[42]
where 42 is the size of the array. In this case you'd probably want it to work with any size of array, so you'll need to make the size a template parameter like this:
template <typename T, size_t N>
void print_array(T (&arr)[N]) {
...
}
Now you don't even need to use the sizeof
trick to get the length of the array, you can just use N
.
The downside of this approach is that you'll only be able to use the method with variables of actual array types, so you won't be able to use it with arrays that have been allocated using new
(as those would only be accessible through pointers - not directly through a variable). Of course that is true when using the sizeof
trick as well.
If you want your function to be able to work with new
ed arrays too (or generally with arrays that you only have a pointer to), your only option is to take a pointer as your first argument and the size as the second.