user3427150
user3427150

Reputation: 13

Find Item Function Template Giving Me Problems

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.

Upvotes: 0

Views: 283

Answers (2)

Martin J.
Martin J.

Reputation: 5118

Considering that you are trying go pass a const int[] and a const int* as parameters to your template method invocation, and that implicit conversions are not considered for template instantiation, your template function signature should be:

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

e.g.:

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

Alternately, you can change your client code to use non-const int[] and int* parameters, and one of your function template signatures should work.

However, is there a reason why you're not using std::find ?

Upvotes: 0

Oktalist
Oktalist

Reputation: 14714

You are passing a value of type const int[11] as the T* left argument. In an ordinary (non-template) function, this would be OK, as const int[11] can be implicitly converted to const int*, but because find is a template, no implicit conversions are considered. Implicit conversions are considered during overload resolution, but template instantiations happen before overload resolution.

You could force the conversion like this:

const int *pos = CS170::find(static_cast<const int*>(i1), end, item);

Or like this:

const int *pos = CS170::find(i1 + 0, end, item);

Upvotes: 0

Related Questions