Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I return the first element of an array in a template?

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])'
like image 432
template boy Avatar asked Aug 13 '12 22:08

template boy


People also ask

Why can't I return an array?

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.

How do you point the first element in an array?

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 .

How do you return the first element of an array in C++?

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 .

How do you print the first and last elements of an array?

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.


2 Answers

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; 
} 
like image 121
GManNickG Avatar answered Sep 23 '22 03:09

GManNickG


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.

like image 21
user541686 Avatar answered Sep 22 '22 03:09

user541686