11

考虑:

#include <iostream>

template <typename T> T getArray( T &arr ) {
    return *arr;
}

int main() {

    int a[] = {5, 3, 6};

    std::cout << getArray(a);

}

假设打印数组中的第一个元素,但它不起作用。这是为什么?

它给了我错误:

error: no matching function for call to 'getArray(int [3])'
4

4 回答 4

12

的类型aint[3],所以的类型Tint[3]数组不能从函数返回。

在 C++11 中,您可以这样做:

template <typename T>
auto getArray(T &arr) -> decltype(*arr)
{ 
    return *arr; 
} 

或这个:

// requires <type_traits>

template <typename T>
typename std::remove_extent<T>::type& getArray(T &arr)
{ 
    return *arr; 
} 

在 C++03 中,您可以这样做,但并不完全相同:

template <typename T>
T getArray(T* arr /* not really an array */)
{ 
    return *arr; 
} 

或者:

template <typename T, std::size_t N>
T getArray(T (&arr)[N])
{ 
    return *arr; 
} 
于 2012-08-13T22:12:08.697 回答
2

尝试

template <typename T, size_t N>
T getArray( T (&arr)[N] ) {
    return *arr;
}

所以这T是元素的类型,而不是数组。

于 2012-08-13T22:12:18.793 回答
1

It does not even compile on MSVC++ 2010 Express. As I expected, this is because you are using a reference as a parameter, a scalar as a return value and a pointer is passed to the function call. I do not know the exact rules regarding templates (i.e. how exactly the type is determined) but that code has to be confusing the hell out of the compiler. The following code returns what you expected it to return.

#include <iostream>

template <typename T> T getArray( T* arr ) {
    return *arr;
}

int main() {

    int a[] = {5, 3, 6};

    std::cout << getArray(a);

}
于 2012-08-13T22:12:20.590 回答
1

Could you try :

#include <iostream>

template <typename T> T getArray( T arr[] ) {
    return *arr;
}

int main() {

    int a[] = {5, 3, 6};

    std::cout << getArray(a);

}
于 2012-08-13T22:14:26.953 回答