简体   繁体   English

为什么我不能在模板中返回数组的第一个元素?

[英]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])'

The type of a is int[3] , so the type of T is int[3] . 的类型的aint[3]所以类型Tint[3] Arrays cannot be returned from functions. 无法从函数返回数组。

In C++11, you can do this: 在C ++ 11中,您可以这样做:

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: 在C ++ 03中你可以做到这一点,但它并不完全相同:

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. 所以T是元素的类型,而不是数组。

It does not even compile on MSVC++ 2010 Express. 它甚至不能在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 (ie 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);

}

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM