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

arrays, c++, templates

Solution

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; 
} 

Problem

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])' ```

Original source