Problem: overload the default <<
operator for a vector<int> v
variable, so that cout << v
will print each element sequentially. Here I saw one option as proposed by Jason Iverson in the previous question
template<typename T>
std::ostream& operator<<(std::ostream& s, std::vector<T> t) {
s << "[";
for (std::size_t i = 0; i < t.size(); i++) {
s << t[i] << (i == t.size() - 1 ? "" : ",");
}
return s << "]" << std::endl;
}
Obviously this should work for any type of elements, however since I am only concerned with int
, I simplified the function as
ostream& operator << (ostream &os, const vector<int> &v){
for (auto x: v){
os << " " << x;
}
return os;
}
It just works fine.
So my question is
- As far as
vector<int> v
is concerned, what is the caveat of not usingtemplate
? - Apart from being general-purpose, what is the advantage of Jason's solution?
Thanks!
Deeper thoughts:
The above question was poorly phrased, and thanks to the comments, I believe it makes sense to rephrase it.
Question: in C++, what is the cost of using template
where a single-type function is enough?
Credits to @Marco A and @Walter, this question could be closed.