0

I am trying to find an item in a range so I have multiple tests for my templated function called "find".

template <typename T> T*  find(T *left, T *end, T item);

that is the function prototype I am using that fails to work with my first test which is:

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;
}

It says @ const int *pos "Error: no instance of function template "find" matches the argument list argument types are (const int [11], const int *, const int)"

I have a second prototype that works with this test but its not fully templated so It fails the second test which asks for a int *pos not a const int *pos.

second prototype:

template <typename T> const int* find(T *left, T *end, const int item);

I'm not quite sure how I'm supposed to template the first function to work with any case.

4

2 回答 2

0

考虑到您正在尝试将 aconst int[]和 aconst 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;
}

或者,您可以更改您的客户端代码以使用非常量int[]int*参数,并且您的函数模板签名之一应该可以工作。

但是,你不使用有什么原因std::find吗?

于 2014-03-27T00:39:21.273 回答
0

您正在传递一个类型的值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);
于 2014-03-27T01:59:09.453 回答