7

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;
}
Lea
  • 71
  • 4

1 Answers1

7

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.

Live Example

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].

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • 1
    Could you elaborate on what you did?, What standard is this syntax? And will it work on any kind of array? – Lea Feb 15 '17 at 05:28
  • I hope this is clearer after editing. I hope it helps you. – Mohit Jain Feb 15 '17 at 05:45
  • `T &arr[N]` is an array of references [which is illegal](http://stackoverflow.com/questions/5460562/why-it-is-impossible-to-create-an-array-of-references-in-c), but `T (&arr)[N]` is a reference to `T` array which is perfectly valid. – frogatto Feb 15 '17 at 06:22
  • @HiI'mFrogatto Thanks for the link – Mohit Jain Feb 15 '17 at 08:22