[英]error C2893: Failed to specialize function template
I am getting this error and another error too ** "IntelliSense: no instance of function template matches the argument list"** when compiling the following code 我收到此错误和另一个错误**“智能感知:没有函数模板的实例匹配参数列表”**编译以下代码时
I know there might be logic mistakes in my function but I need to solve this error first to be able to debug my function . 我知道我的函数可能存在逻辑错误,但我需要首先解决此错误才能调试我的函数。
#include <iostream>
using namespace std;
template<class T>
T myMax (T& arr ,int arrStart ,int arrSize)
{
if(arrStart==arrSize-1)
return arr[arrSize];
int median = (arrStart+arrSize)/2 ;
T left , right , maximum ;
left = max(arr,arrStart , median);
right = max(arr , median+1 , arrSize-1) ;
if (left>right)
maximum = left;
else
maximum = right ;
return maximum ;
}
void main()
{
int arrSize = 5;
int arr[] = {1,3,4,6,22};
int x;
x = myMax(arr,0,arrSize);
}
The argument for parameter arr
is of type int[5]
. 参数
arr
的参数类型为int[5]
。 Since you didn't specify a template argument for T
when calling myMax
, argument deduction happens and T
is deduced to be int[5]
. 由于在调用
myMax
时没有为T
指定模板参数,因此会发生参数推断,并推导出T
为int[5]
。
Then the compiler attempts to specialize the function template with T = int[5]
(ie, it tries to replace all instances of T
with int[5]
). 然后编译器尝试使用
T = int[5]
来专门化函数模板(即,它尝试用int[5]
替换T
所有实例)。 This fails because the function returns a T
by value but it is not possible to return an array (like int[5]
) by value. 这会失败,因为函数返回
T
值,但不能按值返回数组(如int[5]
)。
It looks like you want T
to be the element type. 看起来你希望
T
成为元素类型。 If that is the case, you can explicitly take a reference to the array, eg, 如果是这种情况,您可以显式地获取对数组的引用,例如,
template<class T, unsigned N>
T myMax (T (&arr)[N])
Though, a more idiomatic way to write the function would be to have it take a pair of random access iterators and have it return an iterator pointing to the "max" element: 但是,编写函数的更惯用的方法是使用一对随机访问迭代器并让它返回指向“max”元素的迭代器:
template <typename RandomAccessIt>
RandomAccessIt myMax (RandomAccessIt first, RandomAccessIt last)
first
is an iterator to the first element in the range and last
is an iterator to one-past-the-end of the range, as is idiomatic for the STL algorithms. first
是范围中第一个元素的迭代器, last
是范围的一个结尾的迭代器,对于STL算法来说是惯用的。 Pointers are usable as random access iterators, so this function can be called as 指针可用作随机访问迭代器,因此可以将此函数称为
int* pointerToMaxElement = myMax(arr, arr + arrSize);
The advantage of the iterator approach is that it works with any random access range, including an array, std::vector
, std::array
, and std::deque
. 迭代器方法的优点是它适用于任何随机访问范围,包括数组,
std::vector
, std::array
和std::deque
。
From a quick look, the two things that jump out at me are: 从快速的角度来看,突然出现的两件事是:
myMax<int>(...)
) Edit - as Mark B points out, this isn't required however myMax<int>(...)
) 编辑 - 正如Mark B指出的那样,这不是必需的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.