Reputation: 71
I'm having a function of finding max and I want to send static array via reference, Why isn't this possible?
template <class T>
T findMax(const T &arr, int size){...}
int main{
int arr[] = {1,2,3,4,5};
findMax(arr, 5); // I cannot send it this way, why?
return 0;
}
Upvotes: 7
Views: 169
Reputation: 30489
Use correct syntax. Change signature to:
template <class T, size_t size>
T findMax(const T (&arr)[size]){...}
Or you can use std::array
argument for findMax()
function.
Why isn't this possible?
const T &arr
: Here arr
is a reference of type T
and not the reference to array of type T
as you might think. So you need [..]
after arr
. But then it will decay to a pointer.
Here you can change the binding with ()
and use const T (&arr)[SIZE]
.
For more, you can try to explore the difference between const T &arr[N]
v/s const T (&arr)[N]
.
Upvotes: 7