Addy
Addy

Reputation: 17

How do I make my template require only absolutely necessary functions

Sorry new poster here and really couldn't phrase my question particularly well. Also apologize for any breaches in etiquette ahead of time. I am working on templatizing a class. I pass two tests on it but I fail the third test: This class provides a minimal set of operations and, as such, represents a test of whether your MiniMax class requires its data to support more functions than are absolutely necessary.

template <class Data>
void MiniMax<Data>::observe (const Data& t)
{
  if (count == 0)
    min = max = t;
  else
    {
      if (t < min)
    min = t;
      if (t > max)
    max = t;
    }
  ++count;
}

It fails at the line if(t>max) with no match for operator> during compilation. How do I alter my template so it doesn't require > to be implemented in the user-defined class? In this assignment, I can only edit the template and not any of the test drivers.

Upvotes: 0

Views: 41

Answers (1)

phantom
phantom

Reputation: 3342

As @Anthony Sottile said in the comments the simplest way to do this would be to switch the placement of the operands and change the operator, changing t > max to max < t. This reuses the operator and still does the same thing.

After changing it your code would look like this:

if (count == 0)
   min = max = t;
else
{
    if (t < min)
        min = t;
    if (max < t) // <-- Difference Here
        max = t;
}
++count;

Upvotes: 1

Related Questions