CS 70

Code for Multiple Types

  • LHS Cow speaking

    On the last page, we wrote a fill function for vector<int>

  • Pig speaking

    I want MORE functions! Can we also have a fill function for list<double>?

We could write a similar fill function for list<double>

Fill in the body of the function. (Hint: It'll be a for loop.)

void fill(vector<double>::iterator startingPoint, vector<double>::iterator pastTheEnd, double val) {
}

Here's how I would implement it:

void fill(list<double>::iterator startingPoint, list<double>::iterator pastTheEnd, double val) {
    for (list<double>::iterator iter = startingPoint; iter != pastTheEnd; ++iter) {
        *iter = val;
    }
}

In essence, we copied the the exact same function from last time, and just changed the type from vector<int> to list<double>.

What do you think about this solution? Slide the slider to indicate your opinion.

Hate it! Love it!

And say a few words about why you feel that way.

Now suppose we might also want to write a fill function for all of these types:

  • vector<double>
  • vector<size_t>
  • list<double>
  • list<int>
  • list<int*>
  • list<int**>
  • list<int***>
  • list<int****>
  • list<Cow*>
  • list<vector<int>>
  • Pig speaking

    Make MORE functions?? What's not to like?

  • Dog speaking

    I'd do it! Especially if we get points for doing it!

What do you think about this solution? Slide the slider to indicate your opinion.

Hate it! Love it!
  • LHS Cow speaking

    Okay… Maybe you're starting to see the problem?

  • RHS Cow speaking

    Lots of times we have a piece of code that could work for multiple types—

  • LHS Cow speaking

    —but is copying that code the best way of doing things?

Because C++ requires us to be so strict about types, it seems like we have to write a separate function for each type, even though they all have the same code in the body.

And, actually, maybe that makes sense. For example, we've seen that the assignment operator does different things for different types. When the compiler converts these different functions into machine language, the code it generates will be very different for each one!

  • RHS Cow speaking

    But still, it feels terrible to have to repeat the same code over and over for every type we might want to work with.

  • LHS Cow speaking

    Thankfully, there is a solution… on the next page.

(When logged in, completion status appears here.)