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;
}
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.
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.
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.
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:
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With