Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by reference to a template function

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;
}
like image 378
Lea Avatar asked Feb 15 '17 05:02

Lea


People also ask

How to pass arguments when calling a function template?

So when calling a function template, there is no need to explictly pass the arguments, on the contrary, it can do harm! Consider the example I gave right at the start: We have reference parameters, so case two described above. This means that the type of the template argument will be the same as the type of the argument without references.

What is pass by reference in C++?

In general, pass by reference is also known as pass by the address of the values declared in the arguments in the calling function relative to the formal arguments of the called function, which can modify the values of the parameters by using this pass by reference which is using the address of the values.

How to pass argument by reference in C++ function?

The ‘&’ symbol is used in the argument of the function to declare the argument by reference. The different ways to pass the argument by reference in C++ function have shown in this tutorial. The way to pass a single argument by reference to a function has shown in the following example.

What is the use of function templates in C++?

Function templates allow writing a single definition that can handle multiple different types. It is a very powerful form of C++’s static polymorphism. When instantiating a class template, we have to pass in the types explictly (at least until C++17): But when instantiating a function template, the compiler can often figure the types out:


1 Answers

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

like image 105
Mohit Jain Avatar answered Oct 13 '22 16:10

Mohit Jain