Code for Multiple Types
On the last page, we wrote a
fill
function forvector<int>
…I want MORE functions! Can we also have a
fill
function forlist<double>
?
We could write a similar fill
function for list<double>
…
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>
.
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>>
Make MORE functions?? What's not to like?
I'd do it! Especially if we get points for doing it!
Okay… Maybe you're starting to see the problem?
Lots of times we have a piece of code that could work for multiple types—
—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!
But still, it feels terrible to have to repeat the same code over and over for every type we might want to work with.
Thankfully, there is a solution… on the next page.
(When logged in, completion status appears here.)