I think Philipp's answer is the best answer. However you can make your own templated operator<<()
that will work for vectors and other standard containers if you want:
// Will write out any container that has begin(), end() and a const_iterator type
template <typename C>
std::ostream& output_container(std::ostream& os, C const& c) {
for (typename C::const_iterator i = c.begin(); i != c.end(); ++i) {
if (i != c.begin()) os << ", ";
os << *i;
}
return os;
}
// Overload operators for each container type that forward to output_container()
template <typename T>
std::ostream& operator<<(std::ostream& os, vector<T> const& c) {
return output_container(os, c);
}
template <typename T>
std::ostream& operator<<(std::ostream& os, list<T> const& c) {
return output_container(os, c);
}
Although you could simply rename output_container()
to operator<<()
and get rid of the per-container-type operator<<()
templates, thereby catching all attempts to use <<
on a class type, this could possibly interfere with operator<<()
function templates for other types.