找到项目函数模板给我的问题



我试图在一个范围内找到一个项目,所以我有多个测试我的模板函数名为"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呢?

最新更新