找到项目函数模板给我的问题
Find Item Function Template Giving Me Problems
我试图在一个范围内找到一个项目,所以我有多个测试我的模板函数名为"find"。
template <typename T> T* find(T *left, T *end, T item);
这是我正在使用的函数原型,它无法与我的第一个测试一起工作,即:
static void TestFind1(void)
{
cout << "***** Find1 *****" << endl;
const int i1[] = {-1, 2, 6, -1, 9, 5, 7, -1, -1, 8, -1};
int size = sizeof(i1) / sizeof(int);
const int *end = i1 + size;
CS170::display(i1, end);
const int item = 9;
const int *pos = CS170::find(i1, end, item);
if (pos != end)
cout << "Item " << item << " is " << *pos << endl;
else
cout << "Item " << item << " was not found" << endl;
}
上面写着@ const int *pos "错误:没有函数模板"find"的实例匹配参数列表参数类型为(const int [11], const int *, const int)"
我有第二个原型,与这个测试工作,但它没有完全模板化,所以它失败了第二个测试,要求int *pos不是const int *pos。
第二个原型:
template <typename T> const int* find(T *left, T *end, const int item);
我不太确定我应该如何模板第一个函数与任何情况下的工作
您正在传递const int[11]
类型的值作为T* left
参数。在普通(非模板)函数中,这是可以的,因为const int[11]
可以隐式转换为const int*
,但由于find
是模板,因此不考虑隐式转换。在重载解析期间考虑隐式转换,但模板实例化发生在重载解析之前。
你可以这样强制转换:
const int *pos = CS170::find(static_cast<const int*>(i1), end, item);
或者像这样:
const int *pos = CS170::find(i1 + 0, end, item);
考虑到您正在尝试将const int[]
和const int*
作为参数传递给模板方法调用,并且不考虑模板实例化的隐式转换,您的模板函数签名应该是:
template <typename T>
const T* find(const T *left, const T *end, const T& item);
例如:
template <typename T>
const T* find(const T *left, const T *end, const T& item) {
while (left != end) {
if (item == *left) {
return left;
}
++left;
}
return end;
}
或者,您可以更改您的客户端代码以使用非const int[]
和int*
参数,并且您的函数模板签名之一应该工作。
但是,您为什么不使用std::find
呢?
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- C++出现控制台错误.我无法识别源代码的问题
- 我的逻辑反转字符串中的元音有什么问题?
- C++ 每次运行程序时我都会"nan"输出的问题
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 我的超类中的模板问题与结构定义
- C++关于ENUM的问题。我得到的响应比枚举列表大
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 我的问题是关于C++中数字和序列的重复以及如何打印它们?
- C++无法解决我的问题。我有控制台错误
- 我应该在 main 函数中写什么来测试我的问题?
- 什么是非营利组织???我的问题是我不明白为什么有人会使用它
- 圆形与方形碰撞检测以及需要响应C++ |OpenGL。我的问题就是这个"I need to keep the circle outside the square"
- 为什么我的C 问题没有获得所需的输出
- 我的问题是关于类成员函数作为类指针的返回类型
- **编译器错误** - getline() 函数不接受第一个参数"std:ifstream"是什么我的问题?
- 找到项目函数模板给我的问题