[英]Non-type parameter in function template
I've a very simple template function, but there's confusion as to how to instantiate/call the function because of the non-type parameter. 我有一个非常简单的模板函数,但是由于非类型参数,在如何实例化/调用该函数方面存在困惑。 The definition of the template function is as goes:
模板函数的定义如下:
template<typename Glorp, int size>
Glorp min(Glorp array[size])
{
Glorp minival = array[0];
for (int i = 0; i < size; i++)
if (array[i] < minival)
minival = array[i];
return minival;
}
Now, in main()
I have the following code: 现在,在
main()
我有以下代码:
void main()
{
const int size=5;
int array[size];
for (int i = 0; i < size; i++)
cin >> array[i];
int p = min(array[size]);
cout << p;
}
This gets me the error message: 这使我收到错误消息:
Error 1 error C2783: 'Glorp min(Glorp *)' : could not deduce template argument for 'size' c:\users\tamara\documents\visual studio 2013\projects\nuevoprojecto\nuevoprojecto\main.cpp 23 1 NuevoProjecto
How DO I call this function from main()
? 如何从
main()
调用此函数? I can't find the answer for this, the only examples I saw were for non type parameters in template classes 我找不到答案,我看到的唯一示例是模板类中的非类型参数
I see two major problems in you code 我在您的代码中看到两个主要问题
1) the syntax for a template function receiving an array, deducing the type and the size, is the following 1)模板函数接收数组的语法,推导类型和大小,如下所示
template <typename Glorp, int size>
Glorp min (Glorp (&array)[size])
{
// ...........^^^^^^^^
}
2) you have to call it without [size]
2)您必须不带
[size]
来调用它
int p = min(array[size]); // wrong
int p = min(array); // correct
because passing array[size]
you're trying to pass a single int
from an un-allocated memory position (correct array
values are from array[0]
to array[size-1]
). 因为传递
array[size]
您试图从未分配的内存位置传递单个int
(正确的array
值是从array[0]
到array[size-1]
)。
A minor problem: main()
return a int
, not a void
. 一个小问题:
main()
返回一个int
,而不是一个void
。
Off topic suggestion: if you can use at least C++11, consider using std::array
, instead of old C-style arrays, whenever possible. 脱离主题的建议:如果可以至少使用C ++ 11,请考虑尽可能使用
std::array
而不是旧的C样式数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.