Is there any way of creating a function that accepts any version of a given
template class?
e.g. this works:
ostream& operator << (ostream &out,const Vector<int>& vec);
but this doesn’t:
ostream& operator << (ostream &out,const Vector& vec);
Is it possible to get the second line to work somehow for any version of vector?
e.g. vector<int> and vector<double> without having to write 2 separate functions?
Added to question:
I’ve made op<< a template function like you’ve suggested. In order to make it a friend function of the vector class I tried adding the following to the Vector class definition, but it didn’t work:
friend ostream& operator << (ostream &out, const Vector<T>& vec);
any ideas what can be done to fix it?
As already pointed out something like this should work:
As for the friend requirement, that is most easily handled like this:
However, normally I would think of any output operator like this that requires access to the internals of the class to be showing you a mistake in your
Vectorclass. It really only ought to need to use the public interface to do the display.The other thing is that you might also want to template the output stream itself so that you can preserve its type:
The
Vector‘sprint_oncan still useostream.