Consider:
#include <iostream>
template <typename T> T getArray( T &arr ) {
return *arr;
}
int main() {
int a[] = {5, 3, 6};
std::cout << getArray(a);
}
It's suppose to print the first element in the array but it is not not working. Why is that?
It gives me the error:
error: no matching function for call to 'getArray(int [3])'
Arrays cannot be passed by value, therefore they cannot be returned. As to why arrays cannot be passed by value: this was a design decision made by K&R when they were first designing the language, and it's too late to change it now because all the existing C code would break.
To assign a pointer to the array we can use the following declaration... int a[10]; int *pa = &a[0]; Basically this assigns the memory address of a[0] the first element in array a to pointer of type int .
To get the first element (20) from the array, we can use the subscript operator [ ] by passing an index 0 . In C++ arrays are zero-indexed, so the first element index of an array is 0 .
Use the Array.at() method to get the first and last elements of an array. For example, arr.at(0) returns the first element and arr.at(-1) returns the last array element.
The type of a
is int[3]
, so the type of T
is int[3]
. Arrays cannot be returned from functions.
In C++11, you can do this:
template <typename T>
auto getArray(T &arr) -> decltype(*arr)
{
return *arr;
}
Or this:
// requires <type_traits>
template <typename T>
typename std::remove_extent<T>::type& getArray(T &arr)
{
return *arr;
}
In C++03 you can do this, but it's not quite the same:
template <typename T>
T getArray(T* arr /* not really an array */)
{
return *arr;
}
Or:
template <typename T, std::size_t N>
T getArray(T (&arr)[N])
{
return *arr;
}
Try
template <typename T, size_t N>
T getArray( T (&arr)[N] ) {
return *arr;
}
so that T
is the type of the element, not the array.
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