简体   繁体   English

函数模板中的数组类型推导

[英]Array type deduction in a function template

I have a template method as follows:- 我有一个模板方法如下:

template<typename T, int length>
void ProcessArray(T array[length]) { ... }

And then I have code using the above method:- 然后我有使用上述方法的代码:

int numbers[10] = { ... };
ProcessArray<int, 10>(numbers);

My question is why do I have to specify the template arguments explicitly. 我的问题是为什么我必须显式指定模板参数。 Can't it be auto-deduced so that I can use as follows:- 不能自动推断出它,以便我可以使用以下方法:-

ProcessArray(numbers); // without all the explicit type specification ceremony

I am sure I am missing something basic! 我确定我缺少基本的东西! Spare a hammer! 备用锤子!

You can't pass arrays by value. 您不能按值传递数组。 In a function parameter T array[length] is exactly the same as T* array . 在函数参数T array[length] T* array 完全相同 There is no length information available to be deduced. 没有可推论的长度信息。

If you want to take an array by value, you need something like std::array . 如果要按值获取数组,则需要类似std::array东西。 Otherwise, you can take it by reference, which doesn't lose the size information: 否则,您可以参考它,它不会丢失尺寸信息:

template<typename T, int length>
void ProcessArray(T (&array)[length]) { ... }

You're missing the correct argument type: arrays can only be passed by reference : 您缺少正确的参数类型:数组只能通过引用传递:

template <typename T, unsigned int N>
void process_array(T (&arr)[N])
{
    // arr[1] = 9;
}

double foo[12];
process_array(foo); // fine

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

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